向嵌套对象添加属性 - Javascript

时间:2013-10-28 17:13:46

标签: javascript object lodash

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

这是我的代码:

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 function

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

  

{num_401510_640070:'[object Object] [object Object]'}

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

2 个答案:

答案 0 :(得分: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
    });        
}

答案 1 :(得分: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;  

  }