2013-10-28 215 views
3

我试图创建一个具有多个对象的对象。然后我需要为这些嵌套对象添加属性。向嵌套对象添加属性 - Javascript

这里是我的代码:

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

仅供参考,​​是Lodash function

当我运行这个,它基本上创建两个嵌套在每个key的对象内的对象。 实施例当console.log() ED:

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

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

回答

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

太棒了。我不知道这种方法。完美作品 – JDillon522

+0

@ JDillon522:说实话,我从来没有用过lodash。我只是通过他们的文档快速浏览一下。只是说... ;-) –

+2

哈。我刚刚拿到Bazinga'd – JDillon522

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; 

    } 
+0

蓝天回答似乎更合适,但如果你已经在使用lodash图书馆了。 – aug

+0

同意。没有lodash这将工作,我相信(我没有尝试它) – JDillon522