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?
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.
var obj = Object. assign(obj, loc) is the way out here. use like obj. leftArray=[]; which automatically generate new obj.
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.
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.
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 }
You could do this:
for(var key in options) {
products[key] = options[key];
}
That would effectively combine the two objects' variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With