我一直在寻找可以帮助我解决此特定问题的方法,但是我没有找到适合我情况的合适解决方案。如果有人能指出我正确的方向,我将不胜感激。
我有一个数组:
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Juan Nieto",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Bani Cortes",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Medina Marquez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
}
]
}
]
}
];
我还有另一个创建对象的函数,我想做的就是将该对象插入到特定索引处的“树”中。因此,例如,用户将选择在“ Ruiz Hernandez”下方插入一个新用户,因此我将创建一个对象,该对象将是“ Checking”的同级对象。但是我希望它具有足够的灵活性,以便如果有人添加作为“检查”的子代,我们将做同样的事情,或者如果添加“ Bani Cortes”的子代,我们也将做同样的事情。
我认为我必须迭代ruizTreeData
直到找到“ Ruiz Hernandez”,然后将对象插入“ {Ruiz Hernandez”的children
数组中。
因此数组将如下所示:
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
}...
]
},
{
"Name": "Inserted object",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png"
}
]
}
];
我尝试了很多事情,最接近的是:
positionInTree = ruizTreeData
.map(function (element) {return element["Name"];})
.indexOf("Ruiz Hernandez");
但这仅在第一个索引处返回,不会进入嵌套对象。为此,我需要一个for
循环吗?
我非常感谢您的帮助。非常感谢。
答案 0 :(得分:1)
你去了。您可以通过键/值标识符选择元素,如果该对象中没有对象,则此函数将创建一个children属性,或者将对象添加到现有的children属性中。
我在最后一个节点(Checking的孩子)中添加了一个名叫Ruiz Hernandez的人,向您展示了该函数如何在具有键/值标识符的每个节点中添加对象。
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Juan Nieto",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Bani Cortes",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Ruiz Hernandez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Medina Marquez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
}
]
}
]
}
];
Array.prototype.addChild = function(key, value, object){
let el;
if(this.find(x => x[key] == value)){
this.filter(x => x[key] == value).forEach(y => y.children = (y.children) ? [...y.children, {...object}] : [{...object}])
}
this.forEach(y => {
if(y.children){
y.children.addChild(key, value, object);
}
});
}
ruizTreeData.addChild("Name", "Ruiz Hernandez", {Name: "Name"});
console.log(ruizTreeData);