我编写了这个简单的代码,该代码解构了一个对象数组,以便根据每个键构建新的数组.我正在学习ES6,并希望使用解构将其重构为一行代码,但我也不太了解.
let candles = [{
open: 1,high: 2,low: 0.5,close: 1.5,volume: 200
}];
let open = candles.map(x => x.open);
let high = candles.map(x => x.high);
let low = candles.map(x => x.low);
let close = candles.map(x => x.close);
let volume = candles.map(x => x.volume);
console.log(open,high,low,close,volume);
我认为它应该看起来与此类似?
let [open,volume] = candles.map(key => key.value);
最佳答案
这是使用Array.prototype.reduce()的解决方案:
@H_502_31@ 原文链接:https://www.f2er.com/js/531123.htmlconst candles = [{open: 1,close: 2,low: 3,high: 4,volume: 5},{open: 6,close: 7,low: 8,high: 9,volume: 10}];
const result = candles.reduce((a,v) => {
Object.keys(v).forEach(k => (a[k] = a[k] || []).push(v[k]));
return a;
},{});
console.log(result);