I'm trying to create an object that has multiple objects. I then need to add properties to those nested objects.
Here is my code:
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
};
}
});
FYI, _.each() is a Lodash function.
When I run this, it basically creates two objects nested inside of each key's object.
Example when console.log()ed:
{ num_401510_640070: '[object Object][object Object]' }
My goal is to be able to check for the if condition, add it to the object, and then add the remaining portion and have it be a single object. Not multiple objects inside of one object.
lodash has a _.merge method.
_.merge(object, [source], [callback], [thisArg])
So in your case:
if (item.aOptions[1]) {
_.merge(collection[key], {
'price' : item.Price || null,
'inStock' : item.InStock || null,
'iPk' : item.id || null
});
}
You can try this.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With