Destructuring objects from an array using map?

后端 未结 3 710
滥情空心
滥情空心 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:45

    So you should start with reduce first and return an object. Then you can use destructuring on that. Here's an example:

    const candles = [{
      open: 1,
      high: 2,
      low: 0.5,
      close: 1.5,
      volume: 200
    }, {
      open: 2,
      high: 3,
      low: 0.6,
      close: 1.4,
      volume: 300
    }];
    
    const reduction = candles.reduce((acc, candle) => {
      for (let key in candle) {
        if (!(key in acc)) {
          acc[key] = [];
        }
    
        acc[key].push(candle[key]);
      }
    
      return acc;
    }, {});
    
    console.log(reduction);
    // { open: [ 1, 2 ],
    //   high: [ 2, 3 ],
    //   low: [ 0.5, 0.6 ],
    //   close: [ 1.5, 1.4 ],
    //   volume: [ 200, 300 ] }
    
    const {open, high, low, close, volume} = reduction;
    
    console.log(open, high, low, close, volume);
    // [ 1, 2 ] [ 2, 3 ] [ 0.5, 0.6 ] [ 1.5, 1.4 ] [ 200, 300 ]
    

提交回复
热议问题