javascript - 使用 lodash 更新嵌套对象的值

标签 javascript typescript lodash

我有以下嵌套对象(我只添加了 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/

相关文章:

node.js - NestJS e2e 测试模拟 Session 装饰器

javascript - 如何用函数链中的空字符串替换数据库中的空值

javascript - Node.js 模块的编译顺序

javascript - 基于选择元素和 knockout 的 Sammy 路线

javascript - 如何修复错误 "TypeError: cy.[custom command] is not a function"?

javascript - 如何在嵌套映射函数中进行并发异步调用

javascript - 按日期对对象数组进行分组

javascript - 使用 lodash 将数组映射到对象

javascript - window.onerror 和 [对象事件]

javascript - Symfony v2.8 Response($message) 方法 'returning' 超出预期