我有如下的对象数据数组,其中 ID 是对象嵌套数组中的重复键:
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"
}
]
}
}
]
期望以下格式的数据,其中 ID 现在只有一个条目并且嵌套数组也被展平:
[
{
"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"
}
]
我尝试使用Array.flat()
and,Array.flat(Infinity)
但无法处理此数据集。我也尝试使用简单的 for 循环,但没有得到预期的结果。有人能帮忙解决这里缺少的逻辑吗?
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]);
}
}
}
}