首页 > 解决方案 > lodash如何在多个路径中设置值

问题描述

我正在查看 lodash 中的_setand_setWith函数,但我需要能够使用 catch all 参数。

object = {"root": {"a": null, "b": null, "c": null}}};
path = ["root", "*"];
_.set(object, path, 1);

console.log(object)
>>> {"root": {"a": 1, "b": 1, "c": 1}}}

我只展示了一个*,但如果路径有多个,我也需要它工作,例如["root", "*", "*"]

标签: javascriptlodash

解决方案


您可以使用检查是否给出占位符并分叉递归或更新所有键的功能。

function setValue(object, [key, ...rest], value) {
    if (key === '*') {
        Object.keys(object).forEach(rest.length
            ? k => setValue(object[k], rest, value)
            : k => object[k] = value
        );
        return;
    }
    if (rest.length) {
        setValue(object[key], rest, value);
        return;
    }
    object[key] = value;
}

var object = { root: { a: null, b: null, c: null } },
    path = ["root", "*"];

setValue(object, path, 1);

console.log(object);


推荐阅读