How do I merge two dictionaries in Javascript?

Javascript

Javascript Problem Overview


var a = {};
a['fruit'] = "apple";

var b = {};
b['vegetable'] = "carrot";

var food = {};

The output variable 'food' must include both key-value pairs.

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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)

Solution 3 - Javascript

You could use the spread operator in es6, but you would need to use babel to transpile the code to be cross browser friendly.

const a = {};
a['fruit'] = "apple";

const b = {};
b['vegetable'] = "carrot";

const food = { ...a, ...b }

console.log(food)

Solution 4 - Javascript

Create a Utility function which can extend Objects, like:

function extendObj(obj1, obj2){
	for (var key in obj2){
		if(obj2.hasOwnProperty(key)){
			obj1[key] = obj2[key];
		}
	}
	
	return obj1;
}

And then extend this food object with the another Objects. Here is example:

food = extendObj(food, a);
food = extendObj(food, b);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkur GuptaView Question on Stackoverflow
Solution 1 - JavascriptNina ScholzView Answer on Stackoverflow
Solution 2 - JavascriptRohìt JíndalView Answer on Stackoverflow
Solution 3 - Javascriptsynthet1cView Answer on Stackoverflow
Solution 4 - JavascriptAshish KumarView Answer on Stackoverflow