我有一个数组,其中有一个名称和详细信息数组,其中包含电话号码和地点对象。我试图通过循环内部数组来分离父数组。例如我有这个数组 -
const arr = [
{
id: 1,
name: 'Person 1',
details: [
{
phone: 9999999999,
place: 'Mumbai',
},
{
phone: 8888888888,
place: 'Pune'
}
]
},
{
id: 2,
name: 'Person 2',
details: [
{
phone: 7777777777,
place: 'Mumbai',
},
{
phone: 6666666666,
place: 'Pune'
}
]
}
]
我想将数组转换为下面的结果数组,这样我就可以按电话号码升序排序、显示和列出。我现在只需要将数组转换为下面的数组结果 -
const result = [
{
id: 1,
name: 'Person 1',
details: [
{
phone: 9999999999,
place: 'Mumbai',
}
]
},
{
id: 1,
name: 'Person 1',
details: [
{
phone: 8888888888,
place: 'Pune'
}
]
},
{
id: 2,
name: 'Person 2',
details: [
{
phone: 7777777777,
place: 'Mumbai',
}
]
},
{
id: 2,
name: 'Person 2',
details: [
{
phone: 6666666666,
place: 'Pune'
}
]
}
]
请帮忙。
最佳答案
您可以减少初始数组以构造新数组。对于每次迭代,您可以映射 details
将一个人的属性添加到一个新数组中,该数组将包含 phone
和place
,另外还有id
和name
那个人的。
const result = data.reduce((res, {id, name, details}) => {
return res.concat(details.map(detail => ({
id,
name,
details: [detail]
})));
}, []);
console.log(result)
<script>const data=[{id:1,name:"Person 1",details:[{phone:9999999999,place:"Mumbai"},{phone:8888888888,place:"Pune"}]},{id:2,name:"Person 2",details:[{phone:7777777777,place:"Mumbai"},{phone:6666666666,place:"Pune"}]}];</script>
上面,而不是循环遍历 details
并附加到res
,我使用了直接返回 res
的快捷方式与 map 结果连接。
此外,使用展开运算符,您可以执行以下操作:
const result = data.reduce((res, {details, ...person}) => {
return res.concat(details.map(detail => ({
details: [detail],
...person,
})));
}, []);
console.log(result)
<script>const data=[{id:1,name:"Person 1",details:[{phone:9999999999,place:"Mumbai"},{phone:8888888888,place:"Pune"}]},{id:2,name:"Person 2",details:[{phone:7777777777,place:"Mumbai"},{phone:6666666666,place:"Pune"}]}];</script>
关于javascript - 根据子数组映射父数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671488/