Destructuring objects from an array using map?

后端 未结 3 742
滥情空心
滥情空心 2021-01-14 00:31

I have wrote this simple code that destructures an array of objects to build new arrays from each key. I am learning ES6 and would like to refactor it into one line of code

3条回答
  •  滥情空心
    2021-01-14 00:54

    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
    }, {} )
    

提交回复
热议问题