简体   繁体   English

遍历 object 数组并获取值

[英]Loop through array of object and get values

I have below object and i need counts from the byPerson array inside the object.我有以下 object 并且我需要来自 object 内的byPerson数组的计数。 Basically, i want to check the count in each byPerson array elements and get those properties as an array.基本上,我想检查每个byPerson数组元素中的count并将这些属性作为数组获取。

for eg例如

var Closed = [16, 0, 1, 43] // here 1st count object has 16 as closed, 2nd count object has no closed property (so we set it to 0), 3rd one has value 1 and 4th one has value 43 var Closed = [16, 0, 1, 43] // 这里第一个count object 有 16 个已关闭,第二个count object 没有关闭属性(因此我们将其设置为 0),第三个值为 1,第四个值为 43

Similarly var Verify = [0, 5, 0, 1]同样 var Verify = [0, 5, 0, 1]

How can i achieve this calculation and stored the results in Closed and Verify variables as shown above.我怎样才能实现这个计算并将结果存储在ClosedVerify变量中,如上所示。

{
  "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"
}

I tried this way我试过这种方式

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. 

You can use Array.reduce to count this in one go:您可以使用Array.reduce在一个 go 中进行计数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM