javascript - 遍历对象数组并获得新的对象数组

我有下面的对象数组,每个对象都有一个 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 只不过是上述数据中的 titlename 的串联。


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);

https://stackoverflow.com/questions/69894299/

相关文章:

javascript - 从数组中创建 N 位随机单词

list - 如何更新 Haskell 中的列表元素

android - 找不到实现(房间)

python - 如何在 python 中删除表的某些行?

c++ - 如何直接从输入流中向集合中插入值?

python - 如何使用 while 循环摆脱空字符串? (Python)

arrays - 为什么文本行数组看起来有一个额外的容器级别?

r - 如何编写一个 apply() 函数来将矩阵列中的每个元素限制为最大允许值?

python - 如何根据字典键和值过滤 Pandas 数据框行?

javascript - discord.js 禁用 “interaction failed”