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?

1

4 Answers 4

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

4 Comments

+1 for hasOwnProperty()! This is the proper way to iterate over an objects properties.
Thanks you've been a great help!
Peter, that ES7 syntax seems to just create a third object containing the two objects as a whole, rather than just their properties
At least in Node.js
5

You could do this:

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

That would effectively combine the two objects' variables.

1 Comment

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!
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

Comments

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/

Comments

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.