首页 > 解决方案 > 更新对象多维数组的值

问题描述

如果我有数组:

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"

标签: javascript

解决方案


您可以在最后迭代索引并更新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; }


推荐阅读