2

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
});
Starboy
  • 1,635
  • 3
  • 19
  • 27
  • Try: `if (collection[thing.Id]) collection[thing.Id].myNewKey = thing.stuff;` – Tushar Sep 03 '15 at 05:01
  • 3
    you wont be able to add repeated keys, that has no sense, instead you can have an array per key, and push repeated elements – bto.rdz Sep 03 '15 at 05:01
  • @bto.rdz I dont want repeated keys, if a key is found already I want to add to it – Starboy Sep 03 '15 at 05:02
  • @bto.rdz to the matched key. IE I have a few items in my JSON that have the same KEY but different values. I need to add those different values but keep the same key. – Starboy Sep 03 '15 at 05:05
  • @bto.rdz your first comment is what I needed, IE: pushing them into an array! Thanks for the insight! – Starboy Sep 03 '15 at 05:15
  • I'd just like to throw this in here in case anyone jumps to the question of whether or not duplicate keys are allowed in the first place. **TL;DR: It depends.** http://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – nbering Sep 03 '15 at 05:26

2 Answers2

2

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];
  }
});
Starboy
  • 1,635
  • 3
  • 19
  • 27
1

In Modern way: maybe someone will come in handy

var collection = {};

angular.forEach(things, function(thing) {
  if(!collection[thing.Id]){
    collection[thing.Id] = [];
  }

  collection[thing.Id] = [...collection[thing.Id], thing.stuff];
  // or ----------------------------------------------------
  // add item at start
  // collection[thing.Id] = [thing.stuff, ...collection[thing.Id]];
  // or ---------------------------------------------
  // if you doesn't want to change referrance every time 
  // collection[thing.Id].push(thing.stuff);
});
Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27