我正在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", "*", "*"]
,我也需要它工作
答案 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)