How to merge two dictionaries in javascript?

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

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

var food = {};

The output variable 'food' should contain both key-value pairs.

+4
source share
4 answers

You can use Object.assign.

var a = { fruit: "apple" },
    b = { vegetable: "carrot" },
    food = Object.assign({}, a, b);

console.log(food);
Run codeHide result

For a browser without support, Object.assignyou can iterate over properties and assign 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);
Run codeHide result
+8
source

Ways to achieve:

1. Using JavaScript method Object.assign () .

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

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

var food = Object.assign({}, a, b);

console.log(food);
Run codeHide result

2. Using a 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);
Run codeHide result

3. Using ES6 Distribution Operator .

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

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

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

console.log(food)
Run codeHide result
+3
source

es6, babel -.

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

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

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

console.log(food)
Hide result
+1

Create a Utility function that can expand objects, for example:

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

    return obj1;
}

And then expand this object with foodother objects. Here is an example:

food = extendObj(food, a);
food = extendObj(food, b);
+1
source

Source: https://habr.com/ru/post/1674964/


All Articles