Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge two dictionaries in Javascript? [duplicate]

Tags:

javascript

var a = {}; a['fruit'] = "apple";  var b = {}; b['vegetable'] = "carrot";  var food = {}; 

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

like image 834
Ankur Gupta Avatar asked Apr 17 '17 10:04

Ankur Gupta


People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

How do I merge one dictionary with another?

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.

Which function helps merge dictionary?

Dictionary is also iterable, so we can use itertools. chain() to merge two dictionaries. The return type will be itertools.

How do you combine objects in JavaScript?

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.


2 Answers

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);
like image 72
Nina Scholz Avatar answered Sep 23 '22 10:09

Nina Scholz


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)
like image 43
Creative Learner Avatar answered Sep 23 '22 10:09

Creative Learner