从嵌套的数组中删除对象 [英] remove object from nested array
问题描述
我有一个谱系图看起来像这样:
{ 孩子:[{
名:鲍勃,
孩子:[{
名:山姆,
孩子:[{
名:迈克
孩子:[{
名:埃利亚斯
孩子:[]
},{
名:罗德里格斯
孩子:[]
}]
}]
}]
}]
}
主要孩子
是包含嵌套的子阵列阵列。
如何从这样一个数组中删除一个对象?
可以说,我想名为萨姆删除对象,应该离开我的以下内容:
{
孩子:[{
名:鲍勃,
孩子:[]
}]
}
它是绊倒了我,我不知道如何开始筑巢。
任何帮助或方向一个教程,类似问题都涉及AP preciated。
递归是树工作的好工具。
VAR树= {\r
\r
孩子:[{\r
名:鲍勃,\r
孩子:[{\r
名:山姆,\r
孩子:[{\r
名:迈克\r
孩子:[{\r
名:埃利亚斯\r
孩子:[]\r
},{\r
名:罗德里格斯\r
孩子:[]\r
}]\r
}]\r
}]\r
}]\r
}\r
\r
功能removeFromTree(父母,childNameToRemove){\r
parent.children = parent.children\r
.filter(函数(子){返回child.name!== childNameToRemove})\r
.MAP(函数(子){返回removeFromTree(儿童,childNameToRemove)});\r
回到父母;\r
}\r
树= removeFromTree(树'埃利亚斯')\r
的console.log(树);\r
的document.write(JSON.stringify(树));
\r
本教程看起来很有趣(节二进制树和图形)。我认为它可以帮助你实现你的要求: HTTPS://www.syncano。 IO /博客/数据结构式的JavaScript /
I have a familytree looking like this:
{
"children": [{
"name": "bob",
"children": [{
"name": "sam",
"children": [{
"name": "mike",
"children": [{
"name": "elias",
"children": []
}, {
"name": "rodriguez",
"children": []
}]
}]
}]
}]
}
The main "children"
is an array containing nested child-arrays.
How can I remove an object from an array like this?
Lets say I want to remove the object with the name "sam", that should leave me with the following:
{
"children": [{
"name": "bob",
"children": []
}]
}
Its the nesting that trips me up and i do not understand how to start.
Any help or directions to a tutorial that deals with similar issues are appreciated.
Recursion is a good tool to work with trees.
var tree = {
"children": [{
"name": "bob",
"children": [{
"name": "sam",
"children": [{
"name": "mike",
"children": [{
"name": "elias",
"children": []
}, {
"name": "rodriguez",
"children": []
}]
}]
}]
}]
}
function removeFromTree(parent, childNameToRemove){
parent.children = parent.children
.filter(function(child){ return child.name !== childNameToRemove})
.map(function(child){ return removeFromTree(child, childNameToRemove)});
return parent;
}
tree = removeFromTree(tree, 'elias')
console.log(tree);
document.write(JSON.stringify(tree));
This tutorial looks interesting (section "Binary Trees" and "Graphs"). I think it could help to implement your requirements: https://www.syncano.io/blog/data-structures-in-javascript/
这篇关于从嵌套的数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!