如何把obj3替换掉arr数组里面的info消息,得出res
const arr = [{
content: {
info: {
stu1: {
name: '张三',
age: 12,
school:'南校'
},
stu2:{
name:'李四',
age:12,
school:'北校'
}
}
}
}, {
content: {
info: {
stu1: {
name: '张三',
age: 12,
school:'南校'
},
stu2:{
name:'李四',
age:12,
school:'北校'
}
}
}
}]
const obj3={
info: {
stu1: {
name: '张三',
age: 12
},
stu2:{
name:'李四',
age:12
},
stu3:{
name:'王五',
age:23
}
}
}
根据name值决定是否删除、添加arr中对应项?还是根据stu1,stu2,stu3这种键名称?
下面这个是根据stu1,stu2,stu3这种键名称
///arr和obj3数据
let keys = Object.keys(obj3.info);
arr.forEach(item => {
//新增
keys.forEach(key => {
if (!item.content.info[key]) {
item.content.info[key] = obj3.info[key];
}
});
//删除
Object.keys(item.content.info).forEach(key => {
if (!obj3.info[key]) delete item.content.info[key]
})
});
console.log(JSON.stringify(arr, null, 2))
下面根据name
///得到同一个info下的不重名键名称
function getKey(info) {
let i = 1;
while (true) {
if (!info['stu' + i]) return 'stu' + i
i++;
}
}
let key_names = Object.keys(obj3.info).map(i => ({ key: i, name: obj3.info[i].name }));//得到obj3中的name值和键值对象集合
arr.forEach(item => {
let keys = Object.keys(item.content.info), arrNames = keys.map(i => item.content.info[i].name)
//删除
keys.forEach(key => {
if (!key_names.some(i => item.content.info[key].name == i.name)) delete item.content.info[key]
});
//添加
key_names.forEach(i => {
if (!arrNames.some(x => i.name == x)) item.content.info[getKey(item.content.info)] = obj3.info[i.key];
})
});
console.log(JSON.stringify(arr, null, 2))
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!