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?
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?
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 }
hasOwnProperty()! This is the proper way to iterate over an objects properties.You could do this:
for(var key in options) {
products[key] = options[key];
}
That would effectively combine the two objects' variables.
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!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
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/