Destructuring objects from an array using map?

后端 未结 3 708
滥情空心
滥情空心 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 01:03

    Here's a solution using Array.prototype.reduce():

    const 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);

提交回复
热议问题