3

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.

2 Answers 2

5

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
    });        
}
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. I was unaware of that method. Works perfectly
@JDillon522: To be honest, I've never used lodash. I just took a quick look through their documentation. Just sayin... ;-)
Ha. I just got Bazinga'd
1

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;  

  }

2 Comments

Blue Skies answer seems more appropriate though if you are already using the lodash library.
Agreed. Without lodash this would work I believe (I didnt try it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.