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": "BLR",
"State": "KA"
}
]
}
}
]
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": "BLR",
"State": "KA"
}
]
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]);
}
}
}
}