Search code examples
javascriptnode.jsarraysjavascript-objects

Merging two objects in nodejs


I have following two objects

First:

var a = [{a:1},
 {b:2},
 {c:3}
]

Second:

var b = [{a:1},
 {b:2},
 {c:3}
]

I am trying to merge the objects using following function which I wrote:

var json_concat = async (o1, o2) => {
    return new Promise((resolve, reject) => {
        try {
            for (var key in o2) {
                o1[key] = o2[key];
            }
            resolve(o1);
        } catch (e) {
            reject(e);
        }
    });
}

I am not getting the concatenated object by this. The required result is:

var c = [
{a:1},
{b:2},
{c:3},
{a:1},
{b:2},
{c:3}
]

Please help. Thanks in advance


Solution

  • You don't need to make a specific concat function to get that result. Using Array.concat, you can get the result easily.

    var a = [
      {a:1},
      {b:2},
      {c:3}
    ];
    
    var b = [
      {a:1},
      {b:2},
      {c:3}
    ];
    
    const result = a.concat(b);
    console.log(result);