- list如何变成list1
<script>
const list = [{
"name": "小明",
"userId": "001",
"chinese": 99,
},
{
"name": "小明",
"userId": "001",
"mathematics": 98,
},
{
"name": "小红",
"userId": "002",
"mathematics": 99,
},
{
"name": "小明",
"userId": "001",
"english": 98,
},
{
"name": "小红",
"userId": "002",
"english": 97,
}
]
// const list1 = [{
// "name": "小明",
// "userId": "001",
// "chinese": 99,
// "mathematics": 98,
// "english": 98,
// },
// {
// "name": "小红",
// "userId": "002",
// "mathematics": 99,
// "english": 97,
// }
// ]
2.分析只需新声明一个数组 之后做个判断name和userId不重复的可以push到list1中,重复的利用object.assign()这个方法拷贝到list1中,这个方法的特性就是重复的键和值会默认替换掉,这样就解决了属性值和属性名重复的问题以及数据污染问题
var list1 = []
list.forEach( item => {
var flag = true // 控制是否push到新的数组还是不push
if (list1 && list1.length > 0) {
// 第一次是不需要比较的
for (var i = 0; i < list1.length; i++) {
if (list1[i].name === item.name && list1[i].userId === item.userId) {
Objetc.assgin( list1[i], item)
flag = false // 防止push到新数组
break // 终止循环体
}
}
}
// 直接进入这块
if (flag) {
list1.push(item)
}
})