如果我有数组:
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 - 更新对象多维数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830338/