我有下面的对象数组,每个对象都有一个 projects
属性,该属性还有它的对象数组。
const data = [
{
"title": "Release",
"projects": [
{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}
]
},
{
"title": "Payments",
"projects": [
{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
]
我想遍历它并得到如下结果。 name
只不过是上述数据中的 title
和 name
的串联。
const result = [
{
name: 'Release-Server',
success: 0,
failure: 100,
},
{
name: 'Payments-Platform1',
success: 100,
failure: 0,
},
{
name: 'Payments-Platform2',
success: 50,
failure: 5,
},
];
我尝试了以下方法,但无法弄清楚如何准确获得如上所示的结果。有人可以帮忙吗。
data.forEach(prj => {
prj.projects.forEach((project) => {
// unable to get how to push these details into a new array of object
})
});
最佳答案
您可以执行以下操作(确保添加对 null/undefined 引用的检查)
const data = [{
"title": "Release",
"projects": [{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}]
},
{
"title": "Payments",
"projects": [{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
];
const result = data.flatMap(item =>
item.projects.map(project => ({
name: `${item.title}-${project.name}`,
success: project.result.success,
failure: project.result.failure
})));
console.log(result);
关于javascript - 遍历对象数组并获得新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69894299/