如下方代码所示,我想把赵一、赵二、赵四的hasFinished设置为true,但是打印的结果依然是原始数据,请问是哪里出了什么问题吗?
let moduleId = 2;
let sourceId = 8;
let value = ['赵一','赵二','赵四']
let moduleData = JSON.parse(JSON.stringify([
{
"id": 2,
"name": "镇长一",
"subordinate": [
{
"id": 8,
"name": "村长一",
"subordinate": [],
"childList": [
{
"id": 20,
"name": "赵一",
"hasFinished":true
},
{
"id": 21,
"name": "赵二",
"hasFinished":false
},
{
"id": 23,
"name": "赵三",
"hasFinished":false
},
{
"id": 35,
"name": "赵四",
"hasFinished":false
}
]
}
],
"childList":[]
},
{
"id": 4,
"name": "镇长二",
"subordinate": [
{
"id": 5,
"name": "村长二",
"subordinate": [],
"childList": [
{
"id": 24,
"name": "钱一",
"hasFinished":false
}
]
}
],
"childList":[]
},
{
"id": 9,
"name": "镇长三",
"subordinate": [
{
"id": 11,
"name": "村长三",
"subordinate": [],
"childList": [
{
"id": 36,
"name": "孙一",
"hasFinished":false
}
]
}
],
"childList":[]
},
{
"id": 10,
"name": "镇长四",
"subordinate": [],
"childList":[]
}
]));
let arr = moduleData.map(m => {
if(moduleId === m.id) {
m.subordinate.map(s => {
if(sourceId === s.id) {
s.childList.map(c => {
if (value.includes(c.name)) {
const obj = { ...c };
obj.hasFinished = true;
return obj
}
return c
})
}
return s
})
}
return m
})
console.log('修改数据', arr);
s.childList
map出一个新数组没有重写;改成这样s.childList = s.s.childList.map
ps: 不如用forEach直接修改旧数据,如果不想修改到旧数据上级也需要拷贝一个新的