Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding properties to nested objects - Javascript

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.

like image 441
JDillon522 Avatar asked Jul 14 '26 20:07

JDillon522


2 Answers

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
    });        
}
like image 106
Blue Skies Avatar answered Jul 17 '26 18:07

Blue Skies


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;  

  }
like image 40
aug Avatar answered Jul 17 '26 17:07

aug