Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Javascript Object into another Javascript Object

Tags:

javascript

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?

like image 796
lemon Avatar asked Mar 23 '12 17:03

lemon


People also ask

How do you add one object to another in JavaScript?

Use the object. assign() Method to Append Elements to Objects in JavaScript. The object. assign() method will copy all properties defined in an object to another object, i.e., it copies all properties from one or more sources to the target objects.

How do you add an object value to another object?

var obj = Object. assign(obj, loc) is the way out here. use like obj. leftArray=[]; which automatically generate new obj.

How do you combine two objects?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

Can we create object inside object in JavaScript?

These properties must be unique and the differentiating factors that distinguish an object from another. Now, if you want to create an object within another object, the inner object is created as a property of the outer one, and this inner object can only be accessed using the outer object.


2 Answers

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 }
like image 97
Peter Aron Zentai Avatar answered Oct 22 '22 05:10

Peter Aron Zentai


You could do this:

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

That would effectively combine the two objects' variables.

like image 34
Elliot Bonneville Avatar answered Oct 22 '22 05:10

Elliot Bonneville