If Object key exists add another object to it


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.


var collection = {};

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


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

var collection = {};

angular.forEach(things, function(thing) {
    //Key Exists push into array
    //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