我有以下嵌套对象(我只添加了 2 级示例以保持简单,但它可以是任何深度的级别)。
[{
id: 1,
text: 'one',
children: [{
id: 1.1,
text: 'one point one',
children: []
}]
}]
假设我有一个要查找的 ID,如果 ID 匹配则要替换文本。
如何使用 lodash 实现此目的?
最佳答案
我个人是 lodash 的忠实粉丝,但这里确实没有必要:
data = [{
id: 1,
text: 'one',
children: [{
id: 1.1,
text: 'one point one',
children: [
{id: 123, text: 'blah'}
]
}]
}, {
id: 66,
children: [
{id: 123, text: 'blah'}
]
}];
let update = (id, text) => obj => {
if (obj.id === id)
obj.text = text;
else if (obj.children)
obj.children.forEach(update(id, text));
};
data.forEach(update(123, 'hello'));
console.log(data);
正如另一个答案中所指出的,这会迭代整个树并替换所有找到的 id。如果您想提前退出并仅替换第一个 id,可以像这样调整该函数:
let update = (id, text) => obj => {
if (obj.id === id) {
obj.text = text;
return true;
}
else if (obj.children)
return obj.children.some(update(id, text));
};
关于javascript - 使用 lodash 更新嵌套对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792434/