lemon
lemon

Reputation: 9205

Add Javascript Object into another Javascript Object

Given

options = {
 underscored: true
}

products = {
 foo: bar
}

I'd like to get

products = {
 underscored: true
 foo: bar
}

Is it possible to push an object into another object in Javascript?

Upvotes: 21

Views: 26684

Answers (4)

Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

ES5

<script>
function mix(source, target) {
   for(var key in source) {
     if (source.hasOwnProperty(key)) {
        target[key] = source[key];
     }
   }

}

  mix(options, products);
</script>

ES6 - this will mutate objectToMergeTo

const combinedObject = Object.assign(objectToMergeTo, source1, source2)

ES7 (syntax beauty with spread operator) - this version however creates a new instance, you can't add into an object with spread operator.

const combined = { ...source1, ...source2 }

Upvotes: 47

Biswajit Chatterjee
Biswajit Chatterjee

Reputation: 41

you can use jquery.extend(products,options). jQuery.extend combines two objects, over rides the matching element values in the target object and returns resulting object. For more info :http://api.jquery.com/jquery.extend/

Upvotes: 0

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

You could do this:

for(var key in options) {
    products[key] = options[key];
}

That would effectively combine the two objects' variables.

Upvotes: 5

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

var options = {
    underscored: true
};
var products = {
    foo: 'bar'
};
products.underscored = options.underscored;
alert(products.underscored+":"+products.foo);

put quotes around the 'bar' to make it actually have a value, semi-colons and var on the objects, but you get the point.

EDIT: also worth noting;

products.options = options;
alert(products.options.underscored);//alerts true

Upvotes: 0

Related Questions