lodash如何在多个路径中设置值

时间:2019-03-10 21:01:31

标签: javascript lodash

我正在lodash中查看_set_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", "*", "*"],我也需要它工作

2 个答案:

答案 0 :(得分:1)

您可以使用函数来检查是否提供了占位符,并分叉递归或更新所有键。

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);

答案 1 :(得分:0)

您无法使用_.set进行递归设置。

您可以使用_.mergeWith并编写自己的定制器。

链接到mergeWith