javascript - 更新对象多维数组的值
问题描述
如果我有数组:
var arr = [
{
text: "something",
child: [
{
text: "something child",
child: [..]
},..
]
},..
];
当我有索引数组时,除了通过使用 for() 编辑元素来重建具有更新值的整个数组之外,还有没有更有效的方法:
var index = [0, 0];
去做这个:
arr[0]["child"][0]["text"] = "updated value";
这只是一个小例子,但 arr 有时会是 1 级深度,有时是 12 级等。有时我需要更新的值是在第一级:
arr[0]["text"] = "updated value"
解决方案
您可以在最后迭代索引并更新text
属性。
function update(child, indices, value) {
indices.reduce((o, i) => o.child[i], { child }).text = value;
}
var array = [{ text: "something", child: [{ text: "something child", child: [] }] }];
update(array, [0, 0], 'foo');
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- javascript - 动态下拉菜单在 php 中不起作用,数据未从数据库中获取
- java - 创建存储在本地服务器中的文件的 URI 并以 REST JSON 格式发送 URL
- svm - 如何使用 LDA 生成的文档术语矩阵进行 SVM?
- android - 缓存文件可以用于容量分配吗?(使用位图压缩)
- r - 如何使您闪亮的网络应用程序对移动设备友好?
- android - Android Canvas.drawText()双十进制数无法正确呈现
- c - 在 L3 Netfilter 挂钩中看不到 VLAN 标记
- javascript - 在单选按钮组上使用数据属性来显示文本
- python - 抑制 VS Code 中的 Pylance 类型注释警告
- express - 我不能通过 axios 帮助发布到本地主机吗?