【问题标题】:Loop through array of object and get values循环遍历对象数组并获取值
【发布时间】:2021-07-21 03:18:53
【问题描述】:

我有下面的对象,我需要对象内的 byPerson 数组中的计数。基本上,我想检查每个byPerson 数组元素中的count 并将这些属性作为数组获取。

例如

var Closed = [16, 0, 1, 43] // 这里第一个 count 对象有 16 个已关闭,第二个 count 对象没有关闭属性(所以我们将其设置为 0),第三个有值第 1 和第 4 的值为 43

同样 var 验证 = [0, 5, 0, 1]

我怎样才能实现这个计算并将结果存储在Closed 和Verify 变量中,如上所示。

{
  "byPerson": [
    {
      "personId": "1514903899",
      "firstName": "Yatish",
      "lastName": "Patel",
      "count": {
        "Closed": 16,
      }
    },
    {
      "personId": "1559363884",
      "firstName": "Samuel",
      "lastName": "Chacko",
      "count": {
        "Verify": 5
      }
    },
    {
      "personId": "297895805",
      "firstName": "Tim",
      "lastName": "Altman",
      "count": {
        "Closed": 1
      }
    },
    {
      "personId": "others",
      "firstName": "Others",
      "lastName": "",
      "count": {
        "Closed": 43,
        "Verify": 1
      }
    }
  ],
  "resultDateTime": "2021-04-23T12:14:33.901"
}

我试过这种方式

const closedValues= releaseData.byPerson.map(element => element.count["Closed"] === undefined ? 0: element.count["Closed"]);
const verifyValues= releaseData.byPerson.map(element => element.count["Verify"] === undefined ? 0: element.count["Verify"]);
    ```

But i guess it is not the optimal solution where i have to calculate for each one seperately. 

【问题讨论】:

  • 如果你使用 ES6 并且你的对象被称为“jsonData”: const byPerson = jsonData.byPerson;常量关闭 = [];常量验证 = []; for(let i=0; i
  • @Zak- 添加了我尝试过的代码。不是最佳方式。
  • @ArenTrot -- 因为问题已经结束(我投票决定重新打开).. 我为你创建了一个小提琴HERE 如果这就是你要找的......我会重新打开后回答问题(附解释)

标签: javascript arrays reactjs loops object


【解决方案1】:

您可以使用Array.reduce 一次性计算:

const data = {
  "byPerson": [{
      "personId": "1514903899",
      "firstName": "Yatish",
      "lastName": "Patel",
      "count": {
        "Closed": 16,
      }
    },
    {
      "personId": "1559363884",
      "firstName": "Samuel",
      "lastName": "Chacko",
      "count": {
        "Verify": 5
      }
    },
    {
      "personId": "297895805",
      "firstName": "Tim",
      "lastName": "Altman",
      "count": {
        "Closed": 1
      }
    },
    {
      "personId": "others",
      "firstName": "Others",
      "lastName": "",
      "count": {
        "Closed": 43,
        "Verify": 1
      }
    }
  ],
  "resultDateTime": "2021-04-23T12:14:33.901"
}

const result = data.byPerson.reduce((result, {
  count
}) => {
  result.closed.push(count.Closed || 0);
  result.verify.push(count.Verify || 0);
  return result;
}, {
  closed: [],
  verify: []
});

console.log(result);

【讨论】:

  • 谢谢。这比我的方式好多了。
猜你喜欢
  • 2014-07-12
  • 1970-01-01
  • 2017-07-16
  • 2016-09-07
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2021-10-13
  • 2016-07-28
相关资源
最近更新 更多