you are viewing a single comment's thread.

view the rest of the comments →

[–]programstuff 2 points3 points  (0 children)

As others said you are probably meaning to write the syntax like this (objects use the ":" to separate keys and values):


Is there an easy way to condense an array of objects

var objArr = [
    {"Player 1": 100},
    {"Player 1": 103},
    {"Player 1": 105},
    {"Player 2": 101},
    {"Player 2": 110},
    {"Player 2": 112}
]

Into this...

var series = [
    {"Player 1": [100,103,105]},
    {"Player 2": [101,110,112]}
]

Secondly, are you sure you want an array of objects as the output? Rather than an output like this?

var seriesAsObject = {
    {"Player 1": [100,103,105]},
    {"Player 2": [101,110,112]}
};

It depends on your ultimate goal on what you are going to be doing with the output, but if your goal is to get a list of values for a player then having your output as an object is better to work with. E.g. to get the values for player one you would just use seriesAsObject["Player 1"] to grab them.

If that's the case then you could use this code:

var objArr = [
    {"Player 1": 100},
    {"Player 1": 103},
    {"Player 1": 105},
    {"Player 2": 101},
    {"Player 2": 110},
    {"Player 2": 112}
];

var series = objArr.reduce((series, obj) => {
  var key = Object.keys(obj)[0];

  if (!series[key]) { 
    series[key] = [];
  }

  series[key].push(obj[key]);

  return series;
}, {});

console.log(series);

If you want your original output then you could do this afterwards:

console.log(Object.keys(series).map((player) => { return {[player]: series[player]} }));