我有一组具有无限数量的嵌套子对象的对象,如下所示:
var items = [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
},
{
id: 2,
name: 'Item 2',
children: [],
},
{
id: 3,
name: 'Item 3',
children: [
{
id: 1,
name: 'Item 1',
children: [
id: 2,
name: 'Item 2',
children: [],
]
}
]
}
];
我想更新object with id 2
的每个匹配项,使其名称为"这是一个很酷的对象"。
我不确定这是否需要递归或是否有某种类型的查找和替换。
var newObject = {
id: 2,
name: 'This is a cool object',
children: []
}
我想用新对象替换id为2的任何对象的所有出现(无论其余的对象内容如何)。
我尝试了循环但后来意识到它可能是无限级别的深度。
答案 0 :(得分:3)
使用递归。
var items = [ { "id": 1, "name": "Item 1", "children": [ { "id": 2, "name": "Item 2", "children": [] } ] }, { "id": 2, "name": "Item 2", "children": [] }, { "id": 3, "name": "Item 3", "children": [ { "id": 1, "name": "Item 1", "children": [{ "id": 2, "name": "Item 2", "children": [] }] } ] }];
function loop(array, targetId) {
array.forEach((e) => {
if(e.id === targetId) {
e.name = 'This is a cool object';
}
if (e.children && e.children.length > 0) {
loop(e.children, targetId);
}
});
}
loop(items, 2);
console.log(items);

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

答案 1 :(得分:1)
使用Array filter()方法尝试这一行代码。
function findID(items) {
return items.filter(obj => (obj.id === 2)?obj.name='This is a cool object':findID(obj.children));
}
var res = findID(items);
工作演示
var items = [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
},
{
id: 2,
name: 'Item 2',
children: [],
},
{
id: 3,
name: 'Item 3',
children: [
{
id: 1,
name: 'Item 1',
children: [
{
id: 2,
name: 'Item 2',
children: [],
}
]
}
]
}
];
function findID(items) {
return items.filter(obj => (obj.id === 2)?obj.name='This is a cool object':findID(obj.children));
}
console.log(findID(items));