Add Javascript Object into another Javascript Object

You could do this:

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

That would effectively combine the two objects' variables.


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 }

Tags:

Javascript