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]);
}
}
}
}
3
Answers
You can use map() to iterate over the array and extract the nested properties, then flatten the structure. Here’s how you can transform the array to the desired format:
You can use
Array#map
withArray#reduce
to merge such an object like so