javascript - lodash如何在多个路径中设置值
问题描述
我正在查看 lodash 中的_set
and_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", "*", "*"]
解决方案
您可以使用检查是否给出占位符并分叉递归或更新所有键的功能。
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);
推荐阅读
- laravel - Laravel 6 重定向在中间件中使用时显示文件的完整路径
- wpf - ComboBox MVVM上的WPF绑定枚举
- c++ - 如何重新定义默认工具提示行为?
- reactjs - 我应该将 StencilJS 与 ReactJS 一起使用吗?
- bash - 在变量的引号内回显特定字符串
- vb.net - 从 Winforms 应用程序调用 SSRS 报告
- cassandra - Cassandra: - 新添加的节点在 nodetool 状态中不可见
- python - 在 Django 中查看模型类
- python - SQL Sum() 使用用户输入作为参数进行聚合
- javascript - 从 Whatsapp 测验代码更改共享号码