21

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?

lemon
  • 9,155
  • 7
  • 39
  • 47

4 Answers4

47

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 }
Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71
5

You could do this:

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

That would effectively combine the two objects' variables.

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • This is missing a `hasOwnProperty` check and will produce unexpected results, depending on the two objects. Besides, it will create a global variable `key`, which is bad. Always use the `var` keyword! – jwueller Mar 23 '12 at 22:57
0

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/

0
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
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100