gpt4 book ai didi

javascript - 如何在javascript中将子项添加到现有数组

转载 作者:行者123 更新时间:2023-12-01 03:40:34 26 4
gpt4 key购买 nike

我有一个 JavaScript 数组:

var elements = [ // original hierarhical array to display
{key:10, label:"Web Testing Dep.", open: true, children: [
{key:20, label:"Elizabeth Taylor"},
{key:30, label:"Managers", children: [
{key:40, label:"John Williams"},
{key:50, label:"David Miller"}
]},
{key:60, label:"Linda Brown"},
{key:70, label:"George Lucas"}
]},
{key:110, label:"Human Relations Dep.", open:true, children: [
{key:80, label:"Kate Moss"},
{key:90, label:"Dian Fossey"}
]}
];

如果我想添加一个全新的元素,我可以使用push()。但我想添加一个元素的一部分。例如我想添加

var toAdd = {key:100, label:"Johny Dep"}

致关键 10“网络测试部门”的 children 。是否也可以使用push()

最佳答案

您可以使用迭代和递归方法来阻止插入新对象。

function addToStructure(structure, object, parent) {
structure.some(function iter(a) {
if (a.key === parent) {
a.children = a.children || [];
a.children.push(object);
return true;
}
return Array.isArray(a.children) && a.children.some(iter);
});
}

var elements = [{ key: 10, label: "Web Testing Dep.", open: true, children: [{ key: 20, label: "Elizabeth Taylor" }, { key: 30, label: "Managers", children: [{ key: 40, label: "John Williams" }, { key: 50, label: "David Miller" }] }, { key: 60, label: "Linda Brown" }, { key: 70, label: "George Lucas" }] }, { key: 110, label: "Human Relations Dep.", open: true, children: [{ key: 80, label: "Kate Moss" }, { key: 90, label: "Dian Fossey" }] }];

addToStructure(elements, { key: 100, label: "Johny Dep" }, 10);

console.log(elements);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在javascript中将子项添加到现有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43910502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com