Dan*_*oze 5 javascript ecmascript-6
我写了这个简单的代码,它解构一个对象数组,从每个键构建新数组。我正在学习 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);Run Code Online (Sandbox Code Playgroud)
我在想它应该看起来像这样吗?
let [open, high, low, close, volume] = candles.map(key => key.value);
Run Code Online (Sandbox Code Playgroud)
但这显然是错误的!如果有人可以指导我正确的方法来做这件事,谢谢你的帮助!
let candles = [ {
open: 1,
high: 2,
low: 0.5,
close: 1.5,
volume: 200
} ]
const { open, high, low, close, volume } = candles.reduce( ( accumulator, item ) => {
Object.keys( item ).forEach( key => {
accumulator[ key ] = ( accumulator[ key ] || [] ).concat( item[ key ] )
} )
return accumulator
}, {} )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4926 次 |
| 最近记录: |