Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring objects from an array using map?

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 using destructuring but I dont fully understand how too.

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

I am thinking it should look something along the lines of this?

let [open, high, low, close, volume] = candles.map(key => key.value); 

But it is clearly wrong! Thank you for help if someone can direct me the correct way on doing this!

like image 786
Dan Loze Avatar asked Nov 07 '22 21:11

Dan Loze


1 Answers

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);
like image 80
Robby Cornelissen Avatar answered Nov 10 '22 00:11

Robby Cornelissen