2 回答
TA贡献1852条经验 获得超7个赞
Map 方法仅适用于数组,因此您需要制作地图level1[rtype],
level1[rtype].map()
然后比较名称使用,
if(item.name === updated_data[rtype][0].name) {
item = updated_data[rtype];
}
工作片段如下,
let main_object = [
{
"apple":[
{
"name":"aaaa",
"count":"1",
"filter":{
"type":{
"name":"test3"
}
}
},
{
"name":"bbbb",
"count":"9",
"filter":{
"type":{
"name":"test2"
}
}
}
]
},
{
"orange":[
{
"name":"cccc",
"count":"6",
"filter":{
"type":{
"name":"test"
}
}
}
]
}
]
let updated_data = {
"orange":[
{
"name":"cccc",
"count":"1234",
"type":{
"name":"updated_name"
}
}
]
}
let rtype = 'orange';
const altered =
main_object.map((level1,i) => {
if(level1[rtype] !== undefined){
const data = level1[rtype].map((item,index) => {
if(item.name === updated_data[rtype][0].name) {
item = updated_data[rtype];
}
return item;
})
if(level1[rtype] !== undefined){
level1[rtype] = data;
}
}
return level1;
})
console.log(altered);
TA贡献1830条经验 获得超3个赞
在下面试试这个:
let rtype = 'orange';
main_object = main_object.map(function (item) {
if(Object.keys(item).indexOf(rtype) > -1){
item[rtype][0]['filter']['type']['name'] = updated_data[rtype][0]['type']['name'];
return item
}else {
return item
}
});
console.log(main_object)
添加回答
举报