我需要通過對象列表來查找元素並向根添加新元素,我可以滾動列表並找到元素,但無法將其添加到正確的級別爲對象添加元素
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的元素的子元素。 –