Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

How can i transform array of objects with 2 ellements into 2 arrays?

I need to create 2 arrays form one array with object that consist of 2 elements.

I've got array form axios call:

chartdata: Array [4]
  [{"total":3,"month":9},
   {"total":5,"month":5},
   {"total":9,"month":2},
   {"total":4,"month":1}]

How can i get array of totals and array of months?

Upvotes: 0

Views: 66

Answers (2)

th3n3wguy
th3n3wguy

Reputation: 3747

This is a little bit "fancier" than the other suggestions, but it is not the most efficient solution. If performance is an issue, then you will need to use the map solutions others have posted.

// Your array.
const chartdata = [
  {"total":3,"month":9},
  {"total":5,"month":5},
  {"total":9,"month":2},
  {"total":4,"month":1}
];

// Easy way to get each set of values.
const [totals, months] = chartdata.reduce((current, next) => {
  return [
    current[0].concat(next.total),
    current[1].concat(next.month)
  ];
}, [[], []]);

console.log('Totals:', totals);
console.log('Months:', months);

Upvotes: 1

Ariel Batista
Ariel Batista

Reputation: 144

use the build-in javascript function map twice

totals = chartdata.map(function(item){ return item.total})
months= chartdata.map(function(item){ return item.month})

Upvotes: 1

Related Questions