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

标签 javascript arrays loops object iteration

我有下面的对象数组,每个对象都有一个 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);

关于javascript - 遍历对象数组并获得新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69894299/

相关文章:

javascript - 从数组中删除逗号

javascript - md-select 搜索过滤器基于 ng-value 工作,但应该适用于文本

c - 从 0 到 x 填充 char *array

python - 循环函数直到失败的最佳方法?

javascript - 在 Plotly.js 的多个子图中共享痕迹

javascript - 在插入的手动 div 上应用样式

PHP 多维数组用 KEYS 展平

arrays - java.sql.SQLException : Non supported character set: oracle-character-set-178

c++ - 在 C++ 中使用 std::cin 将 char 传递给 int

c - 循环与其他循环的交互