如果我有数组:
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"
答案 0 :(得分:1)
您可以迭代索引并最后更新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; }
答案 1 :(得分:0)
您可能需要一个递归方法,该方法接受数组,索引和新值作为输入。如果索引数组的长度为1,则它将更新数组中的该元素。如果不是,则使用子数组在索引数组中第一个元素指定的元素上调用该方法,删除第一个元素的索引数组并使用新值。
答案 2 :(得分:0)
一个很好的选择是使用香草for-loop
。
let arr = [ { text: "something", child: [ { text: "something child", child: [] } ] }],
index = [0, 0],
current = undefined;
for(let i = 0; i < index.length; i++) {
if (i === index.length - 1) current[index[i]].text = "Ele from Stack";
else current = (current || arr)[index[i]].child;
}
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
在我看来,这是很难维护的,您应该考虑使用不同的数据结构。但是,您询问了这种解决方案。您可以使用eval(),它非常有效,即使没有额外的安全检查对生产环境也是危险的:
var arr = [{
text: "something",
child: [{
text: "something child",
child: [{
text: "something child",
child: [{
text: "something child",
child: []
}]
}, {
text: "something child",
child: []
}]
},
{
text: "something child",
child: [{
text: "something child",
child: []
}, {
text: "something child",
child: []
}]
}
]
}, {
text: "something",
child: [{
text: "something child",
child: [{
text: "something child",
child: [{
text: "something child",
child: []
}]
}, {
text: "something child",
child: []
}]
},
{
text: "something child",
child: [{
text: "something child",
child: []
}, {
text: "something child",
child: []
}]
}
]
}];
var ind = [0, 1, 0];
var setsomething = 2;
function setChild(ind) {
var ev = "arr";
for (var i = 0; i < ind.length; i++) {
if (i + 1 < ind.length) {
ev += '[' + ind[i] + ']["child"]';
} else {
ev += '[' + ind[i] + ']["text"]'
}
}
ev += '=' + setsomething.toString() + ";";
console.log(ev);
console.log("original array");
console.log(arr);
eval(ev);
console.log("Modified array");
console.log(arr);
}
setChild(ind);