根据对象更新深度嵌套的对象数组:Javascript
2021-10-06
1713
我有一个具有某些属性的深层嵌套对象数组,给定一个对象作为输入,它应该以递归方式更新该对象及其子对象。其格式如下,
const arr = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: false,
value2: false
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: false,
value2: false
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: false,
value2: false
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: false,
value2: false
}
}
];
给定的输入对象将如下所示
const obj = {
name: "parent",
value1: true,
value2: true
};
给定此输入,具有匹配名称的对象应使用
obj
的值更新其及其子对象的
value1
和
value2
输出应如下所示
const result = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: true,
value2: true
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: true,
value2: true
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: true,
value2: true
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: true,
value2: true
}
}
];
我尝试的代码。如何实现相同的输出
const res = arr.map((item) => {
let foundItem = arr.find((item) => item.name === obj.name);
return {
...foundItem,
children: {
value1: obj.value1,
value2: obj.value2
}
};
});
1个回答
您需要一个递归函数来传递所需的父级是否在其祖先之一中被发现。
const arr=[{name:"parent",children:[{name:"child1",children:[{name:"granchild1",children:[],class:"level-2 leaf",config:{name:"granchild1",value1:!1,value2:!1}}],class:"level-1 leaf",config:{name:"child1",value1:!1,value2:!1}},{name:"child2",children:[],class:"level-1 leaf",config:{name:"child2",value1:!1,value2:!1}}],class:"level-0 group",config:{name:"parent",value1:!1,value2:!1}}];
const recurse = (arr, nameToFind, objToMerge, inAncestor = false) => {
return arr.map(obj => {
const mergeThis = inAncestor || obj.name === nameToFind;
const merged = !mergeThis ? obj : { ...obj, config: { ...obj.config, ...objToMerge } };
if (merged.children) {
merged.children = recurse(merged.children, nameToFind, objToMerge, mergeThis);
}
return merged;
});
};
const obj = {
name: "parent",
value1: true,
value2: true
};
const { name, ...objToMerge } = obj;
const result = recurse(arr, name, objToMerge);
console.log(result);
CertainPerformance
2021-10-06