mo_maat
mo_maat

Reputation: 2240

Javascript append array into object with key

I have data like this:

[{ team: 'Team1',
     wins: 1,
     group: GroupA
},{ team: 'Team2',
     wins: 1,
     group: GroupA
},{ team: 'Team3',
     wins: 1,
     group: GroupB
},{ team: 'Team4',
     wins: 1,
     group: GroupB
}]

I want it in this form (I basically want to group the data by some value, in this case "group" and use that value as a key in an object of arrays):

{ GroupA: [{'Team1', wins: 1, group: GroupA},{'Team2', wins: 1, group: GroupA}],
GroupB: [{'Team3', wins: 1, group: GroupB},{'Team4', wins: 1, group: GroupB}]
}

How can I accomplish this?

Here is what I tried and which almost worked, but returns objects:

var newStats = {}
     arrTeamStats.map(function(key,idx){

                var arr = [];

                if(newStats[key.group] == undefined) {
                    arr = key;
                    newStats[key.group] = arr;
                } else {
                else {
                    group = key.group;
                    newStats[group].push(key);
                }
           }

Upvotes: 0

Views: 69

Answers (3)

user8897421
user8897421

Reputation:

First, you're misunderstanding .map(). It's not a general purpose iterator, but rather is used to create a new array from the content of an existing one.

What you can do is simply iterate and add new properties to an object as they're located, and consolidate the content.

var data = [{ team: 'Team1',wins: 1,group: "GroupA"},{ team: 'Team2',wins: 1,group: "GroupA"},{ team: 'Team3',wins: 1,group: "GroupB"},{ team: 'Team4',wins: 1,group: "GroupB"}];

var result = {};
for (const o of data) {
  if (result.hasOwnProperty(o.group)) result[o.group].push([o]);
  else result[o.group] = [[o]];
}

console.log(result);


Or a little more concise like this:

var data = [{ team: 'Team1',wins: 1,group: "GroupA"},{ team: 'Team2',wins: 1,group: "GroupA"},{ team: 'Team3',wins: 1,group: "GroupB"},{ team: 'Team4',wins: 1,group: "GroupB"}];

var result = {};
for (const o of data) result[o.group] = (result[o.group] || []).concat([[o]]);

console.log(result);

Upvotes: 1

Harsh Gupta
Harsh Gupta

Reputation: 4538

You need to reduce your array to return an Object.

arrTeamStats.reduce(function(h, o) {
  h[o.group] = h[o.group] || []
  h[o.group].push(o)
  return h
}, {})

HTH

Upvotes: 4

JellyRaptor
JellyRaptor

Reputation: 755

If you're inclined to use something like Lodash, you could use _.groupBy as follows:

var input = [{ team: 'Team1',
     wins: 1,
     group: 'GroupA'
},{ team: 'Team2',
     wins: 1,
     group: 'GroupA'
},{ team: 'Team3',
     wins: 1,
     group: 'GroupB'
},{ team: 'Team4',
     wins: 1,
     group: 'GroupB'
}];

var output = _.groupBy(input, 'group');
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 0

Related Questions