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 } 
4
  • +1 for hasOwnProperty()! This is the proper way to iterate over an objects properties.
    – jwueller
    CommentedMar 23, 2012 at 22:57
  • Thanks you've been a great help!
    – lemon
    CommentedMar 24, 2012 at 3:01
  • 1
    Peter, that ES7 syntax seems to just create a third object containing the two objects as a whole, rather than just their propertiesCommentedFeb 13, 2017 at 23:08
  • At least in Node.jsCommentedFeb 13, 2017 at 23:08
5

You could do this:

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

That would effectively combine the two objects' variables.

1
  • 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
    CommentedMar 23, 2012 at 22:57
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 
    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/

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.