我尝试使用JavaScript编写一个递归函数,将一个新项目(对象数组)添加到一个存在的数据(未知大小的json)中。
需要一些帮助。
存在的数据: 数据包含节点和子节点。每个子节点可以是更多的子节点或节点(叶)
var data = [
{
key:"root",
children:[
{
key:"a0",
children:[]
},
{
key:"a1",
children:[
{
key:"a10",
children:[]
},
{
key:"a11",
children:[]
},
{
key:"a12",
children:[]
}
],
},
{
key:"a1",
children:[]
}
]
}
]
我要添加到现有数据中的新项目:
var result = [
{key:"a1"},
{key:"a12"},
{key:"21"}
]
添加新项目结束时,数据应如下所示: 每次的结果可能不同,但始终是对象的简单数组。
var data = [
{
key:"root",
children:[
{
key:"a0",
children:[]
},
{
key:"a1",
children:[
{
key:"a10",
children:[]
},
{
key:"a11",
children:[]
},
{
key:"a12",
children:[
{key:"21"}
]
}
],
},
{
key:"a1",
children:[]
}
]
}
]
谢谢
答案 0 :(得分:2)
您可以使用reduce
方法执行此操作,并将初始数组作为累加器传递。
var data = [{"key":"root","children":[{"key":"a0","children":[]},{"key":"a1","children":[{"key":"a10","children":[]},{"key":"a11","children":[]},{"key":"a12","children":[]}]},{"key":"a1","children":[]}]}]
var result = [
{key:"a1"},
{key:"a12"},
{key:"21"}
]
result.reduce((r, e, i, arr) => {
let obj = r && r.find(({key}) => key == e.key);
if (obj && arr[i + 1]) return obj.children
else if (r && !arr[i + 1]) r.push(e)
else return null
}, data[0].children)
console.log(data)
答案 1 :(得分:1)
您可以使用递归解决问题。我已按照以下步骤操作
var data = [
{
key:"root",
children:[
{
key:"a0",
children:[]
},
{
key:"a1",
children:[
{
key:"a10",
children:[]
},
{
key:"a11",
children:[]
},
{
key:"a12",
children:[]
}
],
},
{
key:"a2",
children:[]
}
]
}
];
var result = [
{key:"root"},
{key:"a1"},
{key:"a12"},
{key:"21"}
]
function addChildren(item, result) {
if (!result.length) { return []; }
var res = result.shift();
if (item.some(i => i.key === res.key)) {
return item.map(i => {
if (i.key === res.key) {
return {
key: i.key,
children: addChildren(i.children, result)
};
}
return i;
});
} else {
item.push({
key: res.key,
children: addChildren([], result)
});
}
return item;
}
console.log(addChildren(data, result));