如果Object key存在,则向其添加另一个对象

If Object key exists add another object to it

本文关键字:添加 一个对象 Object key 存在 如果      更新时间:2023-09-26

我正在解析一个相当大的JSON文件,并在一个对象内做一些键:值对。我遇到的问题是,如果我找到一个键,我需要实际添加另一个对象,而不是在它上面写。

的例子:

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

在我收到第一篇文章的一些评论之后,我得出了一个结论:

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];
  }
});

以现代的方式:也许有人会派上用场

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);
});