3

我正在尝试创建一个具有多个对象的对象。然后我需要为这些嵌套对象添加属性。

这是我的代码:

var collection = {};
_.each(context, function(item, key) {
    collection[key] = {
      'color_id'   : item.Options[0].id || null,
      'color_Name' : item.Options[0].Name || null
    };

  if (item.aOptions[1]) { "you have another set of items!"};

    collection[key] += {
      'price'       : item.Price || null,
      'inStock'     : item.InStock || null,
      'iPk'         : item.id || null
    };        
  }
});

仅供参考,_.each()是一个Lodash 函数

当我运行它时,它基本上创建了两个嵌套在每个对象内key的对象。编辑时的示例console.log()

{ num_401510_640070: '[对象对象][对象对象]' }

我的目标是能够检查if条件,将其添加到对象中,然后添加剩余部分并使其成为单个对象。一个对象内没有多个对象。

4

2 回答 2

4

lodash 有一个_.merge方法。

_.merge(object, [source], [callback], [thisArg])

所以在你的情况下:

if (item.aOptions[1]) {
    _.merge(collection[key], {
        'price'       : item.Price || null,
        'inStock'     : item.InStock || null,
        'iPk'         : item.id || null
    });        
}
于 2013-10-28T17:21:32.483 回答
1

你可以试试这个。

  if (item.aOptions[1]) { "you have another set of items!"};

    collection[key].price = item.Price || null;
    collection[key].InStock = item.InStock || null;
    collection[key].iPk = item.id || null;  

  }
于 2013-10-28T17:22:43.410 回答