javascriptarraysobject

Flatten the array of objects and removing duplicate key entry


I have array of objects data as below where ID is duplicate key in nested array of object:

 const arr =  [
      {
        "First Name": "ABC",
        "Last Name": "XYZ",
        "Gender": "MALE",
        "Id": "123",
        "moreDetails": {
          "items": [
            {
              "Id": "123",
              "City": "BLR",
              "State": "KA"
            }
          ]
        }
      },
      {
        "First Name": "Test",
        "Last Name": "Me",
        "Gender": "FEMALE",
        "Id": "12345",
        "moreDetails": {
          "items": [
            {
              "Id": "12345",
              "City": "KAN",
              "State": "UP"
            }
          ]
        }
      }
    ]

Expecting below format data where ID is now with one entry and nested array is also flattened:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "City": "BLR",
    "State": "KA"
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "City": "KAN",
    "State": "UP"
  }
]

I tried using Array.flat() and Array.flat(Infinity) but then do not work on this data set. I have also tried with simple for loop but not getting expected result. Can anyone please help with missing logic here.

const result2 = [];
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
  if(!typeof arr[key].moreDetails === 'object'){
    result2.push(arr[key]);
  }else{
    for(let key2 in arr[key].moreDetails.items){
      result2.push(arr[key2]);
    }
  }
}
}

Solution

  • Iterate the array (arr) with Array.map(), destructure the object, and extract moreDetails. Use Object.assign() with array spread to merge the original object, and the items to a single object:

    const arr = [{"First Name":"ABC","Last Name":"XYZ","Gender":"MALE","Id":"123","moreDetails":{"items":[{"Id":"123","City":"BLR","State":"KA"}]}},{"First Name":"Test","Last Name":"Me","Gender":"FEMALE","Id":"12345","moreDetails":{"items":[{"Id":"12345","City":"KAN","State":"UP"}]}}]
    
    const result = arr.map(({ moreDetails, ...rest }) =>   
      Object.assign({}, rest, ...(moreDetails?.items ?? []))
    )
    
    console.log(result)