我需要通过对象列表来查找元素并向根添加新元素,我可以滚动列表并找到元素,但无法将其添加到正确的级别为对象添加元素
var data = [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4,
"children": [
{
"id": 6
},
{
"id": 7
}
]
},
{
"id": 5
}
];
function findById(data, id, element) {
function iter(a) {
if (a.id === id) {
a.push(element); // ERROR
result = a;
return true;
}
return Array.isArray(a.children) && a.children.some(iter);
}
var result;
data.some(iter);
return result
}
var element = {
"children": [{"id": 6}]
};
findById(data, 5, element);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
https://jsfiddle.net/4nrsccnu/
a.push不做任何事情,因为它不是数组。尝试推入阵列。 –
'a.push'抛出错误,因为'a'是不包含数组的对象。您需要使用'Array.indexOf'在'data'中获取'a'的位置。然后参考:https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index –
你可能试图做到这一点,虽然:' a.children.push'而不是'a.push'这会在你的示例中使id为5的对象具有id为6的元素的子元素。 –