作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!