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

时间:2015-09-03 05:00:03

标签: javascript angularjs

我正在解析一个相当大的JSON文件并在对象中执行一些键:值对。我遇到的问题是,如果我找到一个密钥,我需要实际添加另一个对象INSTEAD写它。

示例:

var collection = {};

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

2 个答案:

答案 0 :(得分:2)

在我在第一篇文章中收到的一些评论后得出结论:

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

答案 1 :(得分:0)

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

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