Search code examples
javascriptarraysobjectarray-merge

Merge 2 arrays of objects based on different key but same value


I have referred questions listed below, but got not related answer.

  1. How can I merge properties of two JavaScript objects dynamically?
  2. merge two json object based on key value in javascript
  3. Merge two array of objects based on a key

I have 2 arrays of objects,

OBJ1 -

[
    {
        "ID": 58895,
        "step": "Outage Agreed w/ Business"
    },
    {
        "ID": 58896,
        "step": "GMLC/E911/CMAS Significant"
    }
]

OBJ2 -

[
    {
        "type": "verification_step",
        "value": "GMLC/E911/CMAS Significant"
    },
    {
        "type": "verification_step",
        "value": "Outage Agreed w/ Business"
    }
]

I want to have the output which contains the both values in the single object based on the value of the string i.e.

[
    {
        "ID": 58896,
        "type": "verification_step",
        "step": "GMLC/E911/CMAS Significant"
    },
    {
        "ID": 58895,
        "type": "verification_step",
        "step": "Outage Agreed w/ Business"
    }
]

Please suggest me the way out. (ES6 solution - much appreciated)

Edit

The 3rd reference which have assiged as duplicate is not the scenario. The key should remain "step" and the data should be merged.


Solution

  • You can use reduce() after combining both the arrays.

    const arr1 = [ { "ID": 58895, "step": "Outage Agreed w/ Business" }, { "ID": 58896, "step": "GMLC/E911/CMAS Significant" } ] 
    
    const arr2 = [ { "type": "verification_step", "value": "GMLC/E911/CMAS Significant" }, { "type": "verification_step", "value": "Outage Agreed w/ Business" } ]
    
    const res = [...arr1,...arr2.map(({value,...rest}) => ({step:value,...rest}))].reduce((ac,a) => {
      let k = a.step;
      ac[k] = {...ac[k],...a} || a;
      return ac;
    },{})
    console.log(Object.values(res))