在多维数组中修改深度值的最有效方法是什么?
我跟随json:
[
{"name":"Series 1","data":[
{"x":1506470700,"y":null},
{"x":1506499200,"y":null},
{"x":1506499500,"y":483981},
{"x":1506499800,"y":504588},
{"x":1506500100,"y":502926},
{"x":1506500400,"y":501161},
{"x":1506500700,"y":506453}]
},{"name":"Series 2","data":[
{"x":1506470700,"y":null},
{"x":1506499200,"y":null},
{"x":1506499500,"y":-490671},
{"x":1506499800,"y":-495593},
{"x":1506500100,"y":-512765},
{"x":1506500400,"y":-479475},
{"x":1506500700,"y":-531689}]
}
]
我想将x值乘以1000.我可以使用此代码处理它,例如:
arrayFromJson.forEach((series) => {
series.data.forEach((dataSet) => {
dataSet.x *= 1000;
});
});
但我想知道是否没有更有效/更优雅的方法来做到这一点。
答案 0 :(得分:2)
使用数组映射:
var arr = [{"name":"Series 1","data":[{"x":1506470700,"y":null},{"x":1506499200,"y":null},{"x":1506499500,"y":483981},{"x":1506499800,"y":504588},{"x":1506500100,"y":502926},{"x":1506500400,"y":501161},{"x":1506500700,"y":506453}]},{"name":"Series 2","data":[{"x":1506470700,"y":null},{"x":1506499200,"y":null},{"x":1506499500,"y":-490671},{"x":1506499800,"y":-495593},{"x":1506500100,"y":-512765},{"x":1506500400,"y":-479475},{"x":1506500700,"y":-531689}]}];
arr.map(it => {
it.data = it.data.map(dt => { dt.x = dt.x * 1000 ; return dt;})
});
console.log(arr);
答案 1 :(得分:1)
您的解决方案完全没问题,但请记住,您正在改变原始数组,这可能会导致一些副作用。
对于不可变解决方案,请使用Array.prototype.map和Object.assign:
var data = [{"name":"Series 1","data":[{"x":1506470700,"y":null},{"x":1506499200,"y":null},{"x":1506499500,"y":483981}]}];
var changedData = data.map(series => {
return Object.assign({}, series, {
data: series.data.map(dataSet => {
return Object.assign({}, dataSet, { x: dataSet.x * 1000 });
})
});
});
console.log(data);
console.log(changedData);

答案 2 :(得分:0)
你可以把它写得更短,没有一些括号和大括号。但是你仍然需要嵌套迭代。
arrayFromJson.forEach(series => series.data.forEach(dataSet => dataSet.x *= 1000));
答案 3 :(得分:0)
假设您当前的代码完全正常, 在es6上,一个(可能更快,更可读)的变体可能是
for( let series of arrayFromJson )
for( let data of series.data )
data.x *= 1000;
on es< 6,' for in'也会工作(假设您不需要有序遍历,但如果这些数组没有额外的自己的支柱......)