现有如下结构数组,要求将具有相同lesson_id和number的对象合并,并更加lang字段动态添加cname、ename键值
newData = [
{
"lesson_id": 56,
"lesson_name": "Adopt a Coaching Mindset",
"lang": 1,
"number": 1
},
{
"lesson_id": 56,
"lesson_name": "采用辅导式思维",
"lang": 2,
"number": 1
},
{
"lesson_id": 205,
"lesson_name": "Build a Coaching Habit",
"lang": 1,
"number": 2
},
{
"lesson_id": 205,
"lesson_name": "培养辅导习惯",
"lang": 2,
"number": 2
}
]
// 以number为标识,如果没有那么在定义的对象中创建它
let newObj = {}
newData.forEach(function (element) {
if (typeof newObj[element.number] === 'undefined') {
newObj[element.number] = {
id: element.lesson_id,
cname: '',
ename: '',
number: element.number
}
}
newObj[element.number][element.lang === 1 ? 'ename' : 'cname'] = element.lesson_name
}, this)
for (let i = 0; i < newObj.length; i++) {
if (newObj[i] === '' || typeof (newObj[i]) === 'undefined') {
newObj.splice(i, 1)
i = i - 1
}
}
let arr1 = []
for (let item in newObj) {
let obj1 = {
id: newObj[item].id,
cname: newObj[item].cname,
ename: newObj[item].ename
}
arr1.push(obj1)
}
return arr1