Search code examples
javascriptarraysobjectconcatenation

Merge two objects in javascript having an array


I have two objects a and b. Each has an array results [] which further contains multiple objects.

I want to merge the results [] array from both the objects into third object c.

I have tried var c = Object.assign(a,b) but I am not getting the result.

Consider following example for reference.

a = {results[{"boys": 50, "girls": 20, "red":10},{boys": 40, "girls": 10, "red":50},{boys": 30, "girls": 10, "red":50}]}

b = {results[{boys": 20, "girls": 30},{boys": 50, "girls": 20},{boys": 70, "girls": 30}]}

I am looking for result as follows

c = {results[{"boys": 50, "girls": 20, "red":10},{boys": 40, "girls": 10, "red":50},{boys": 30, "girls": 10, "red":50},{boys": 20, "girls": 30},{boys": 50, "girls": 20},{boys": 70, "girls": 30}]}

Please help. Thanks in advance


Solution

  • The first thing you need to worry about, before merging two arrays, is making sure that your syntax is correct.

    1. Your JavaScript objects are incorrect. You need a colon (:) following your "results" key.
    2. You are missing opening quotes for your "boys" keys.

    Once you have fixed these issues, merging is as simple as using the spread syntax to create a new "results" array within your c object.

    Unfortunately deep-merging does not exist in ES6, so the following will not work:

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

    Instead, you will need to merge your objects' "results".

    const a = {
      "results": [
        { "boys": 50, "girls": 20, "red": 10 },
        { "boys": 40, "girls": 10, "red": 50 },
        { "boys": 30, "girls": 10, "red": 50 }
      ]
    }
    
    const b = {
      "results": [
        { "boys": 20, "girls": 30 },
        { "boys": 50, "girls": 20 },
        { "boys": 70, "girls": 30 }
      ]
    }
    
    const c = { "results": [ ...a.results, ...b.results ] }
    
    console.log(c);
    .as-console-wrapper { top: 0; max-height: 100% !important; }