If Object key exists add another object to it

Issue

I’m parsing a fairly large JSON file and doing some key:value pairs within an object. Issue I’m having is if I find a key I need to actually add another object to it INSTEAD of writing over it.

Example:

var collection = {};

angular.forEach(things, function(thing) {
  collection[thing.Id] = thing.stuff;
  //thing.stuff is an object
});

Solution

Came to a conclusion after some of the comments I’ve received in the first post:

var collection = {};

angular.forEach(things, function(thing) {
  if(collection[thing.Id]){
    //Key Exists push into array
    collection[thing.Id].push(thing.stuff);
  }else{
    //Key doesn't exist create array for object
    collection[thing.Id] = [thing.stuff];
  }
});

Answered By – Starboy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published