【发布时间】: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