we have a JSON array where we have been able to add a child to "East" but we need to add a child to "Ho" under "Air" .
JSON array is like this
[{
"name":"External Customer",
"id":4,
"parentId":0,
"is_open":true,
"children":[
{
"name":"East",
"id":20,
"parentId":4,
"is_open":true,
"children":[
{
"name":"O",
"id":21,
"parentId":20,
"is_open":true,
"children":[
{
"name":"Ho",
"id":22,
"parentId":21,
"is_open":true,
"children":[
{
"name":"Air",
"id":23,
"parentId":22,
"is_open":true
}
]
}
]
{
"name":"grandchild three",
"id":113,
"children":[]
]}
我们尝试通过以下代码添加“孙子三代”
for(var a = 0; a < data.length; a++) {
for(var b = 0; b < data[a].children.length; b++) {
console.log(data[a].children[b]);
if(data[a].children[b].id == 18) {
data[a].children[b].children.push({
name: "grandchild three",
id: 115,
children: []
});
slSchema.tree=JSON.stringify(data);
slSchema.save(function (err) {
done(err, slSchema);
});
}
}
}
我们现在要做的就是在最后一个子节点上添加一个新的子节点,即“ Ho”。我们已经成功地将一个子节点添加到了“ East”节点。如何使用node.js实现它?预先感谢您的帮助。
答案 0 :(得分:1)
您可以使用递归方法来找到正确的节点,如下所示:
const data = [{
"name":"External Customer",
"id":4,
"parentId":0,
"is_open":true,
"children":[
{
"name":"East",
"id":20,
"parentId":4,
"is_open":true,
"children":[
{
"name":"O",
"id":21,
"parentId":20,
"is_open":true,
"children":[
{
"name":"Ho",
"id":22,
"parentId":21,
"is_open":true,
"children":[
{
"name":"Air",
"id":23,
"parentId":22,
"is_open":true
}
]
}
]
}
]
}]
}];
function addChildToNode(data, nodeId, child) {
if (!Array.isArray(data)) {
return;
}
for(element of data) {
if (element.id === nodeId && element.children) {
element.children.push(child);
} else {
addChildToNode(element.children, nodeId, child);
}
}
}
// The node to add the child to..
let searchNodeId = 22;
let newChild = { name: "New Child", parentId: searchNodeId, id: 10 };
addChildToNode(data, searchNodeId, newChild);
console.log("Result: ", data);