首页 > 解决方案 > 在 Angular 2/4/5/7 中获取 JSON 对象节点数

问题描述

我一直无法获取具有特定值的 JSON 对象的计数,例如 My JSON 是

所以我想统计已部署和失败进程的总数,并将它们显示到字体末尾。

 [{
      "id": "102",
      "username":"User 1",
      "desc": "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s",
      "timeDeployed":"27-MAR-2019 20:21",
      "status": "Deployed"
    },
    {
        "id": "103",
        "username":"User 3",
        "desc": "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
        "timeDeployed":"10-MAR-2019 20:21",
        "status": "Failed"
      },
      {
        "id": "104",
        "username":"User 2",
        "desc":"The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters",
        "timeDeployed":"28-DEC-2019 01:21",
        "status": "Deployed"
      },
      {
        "id": "108",
        "username":"User 1",
        "desc":"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form",
        "timeDeployed":"10-JAN-2019 20:21",
        "status": "Deployed"
      }]

标签: angular

解决方案


您可以使用 Array reduce在循环中获取计数

var rawData = [{ "id": "102", "username":"User 1", "desc": "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s", "timeDeployed":"27-MAR-2019 20:21", "status": "Deployed" }, { "id": "103", "username":"User 3", "desc": "Lorem Ipsum is simply dummy text of the printing and typesetting industry", "timeDeployed":"10-MAR-2019 20:21", "status": "Failed" }, { "id": "104", "username":"User 2", "desc":"The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters", "timeDeployed":"28-DEC-2019 01:21", "status": "Deployed" }, { "id": "108", "username":"User 1", "desc":"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form", "timeDeployed":"10-JAN-2019 20:21", "status": "Deployed" }]

var count = rawData.reduce((acc,eachData) => {
  if (eachData.status === 'Deployed') {
    acc.deployed ++
  } else {
    acc.failed ++
  }
  return acc
}, {deployed: 0, failed: 0})

console.log(count)


推荐阅读