var a = {}; a['fruit'] = "apple"; var b = {}; b['vegetable'] = "carrot"; var food = {};
The output variable 'food' must include both key-value pairs.
You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.
Dictionaries can also be merged by using the unpacking operator (**). It is a unary operator with a dict object as an operand. It adds each k-v pair in an empty dictionary. Obviously, if the second dictionary is also unpacked, the value of the existing key will be updated.
Dictionary is also iterable, so we can use itertools. chain() to merge two dictionaries. The return type will be itertools.
The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.
You could use Object.assign
.
var a = { fruit: "apple" }, b = { vegetable: "carrot" }, food = Object.assign({}, a, b); console.log(food);
For browser without supporting Object.assign
, you could iterate the properties and assign the values manually.
var a = { fruit: "apple" }, b = { vegetable: "carrot" }, food = [a, b].reduce(function (r, o) { Object.keys(o).forEach(function (k) { r[k] = o[k]; }); return r; }, {}); console.log(food);
Ways to achieve :
1. Using JavaScript Object.assign() method.
var a = {}; a['fruit'] = "apple"; var b = {}; b['vegetable'] = "carrot"; var food = Object.assign({}, a, b); console.log(food);
2. Using custom function.
var a = {}; a['fruit'] = "apple"; var b = {}; b['vegetable'] = "carrot"; function createObj(obj1, obj2){ var food = {}; for (var i in obj1) { food[i] = obj1[i]; } for (var j in obj2) { food[j] = obj2[j]; } return food; }; var res = createObj(a, b); console.log(res);
3. Using ES6 Spread operator.
let a = {}; a['fruit'] = "apple"; let b = {}; b['vegetable'] = "carrot"; let food = {...a,...b} console.log(food)
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