javascript - json 数组在键 javascript 中作为计数返回
问题描述
我有一个 json 对象,里面有 json 数组
{
"0": [
{
"accountId": "2020060",
"status": "0"
}
],
"1": [
{
"accountId": "2020025",
"status": "1"
},
{
"accountId": "2020027",
"status": "1"
},
{
"accountId": "2020057",
"status": "1"
}
],
}
如何将 json 数组转换为 count 以使响应看起来像这样?
{
"0" : "1",
"1" : "3"
}
解决方案
如果您的意图只是计算每个索引的数组长度,那么您就可以了,
const obj = {
"0": [{
"accountId": "2020060",
"status": "0"
}],
"1": [{
"accountId": "2020025",
"status": "1"
},
{
"accountId": "2020027",
"status": "1"
},
{
"accountId": "2020057",
"status": "1"
}
],
}
const result = {};
for (const [key, val] of Object.entries(obj)) {
result[key] = val.length
}
console.log("result", result)
另一方面,如果您想根据status
字段进行计数,那么您就可以了,
const obj = {
"0": [{
"accountId": "2020060",
"status": "0"
}],
"1": [{
"accountId": "2020025",
"status": "1"
},
{
"accountId": "2020027",
"status": "1"
},
{
"accountId": "2020057",
"status": "1"
}
],
}
const result = {};
Object.entries(obj).forEach(([key, val]) => {
let count = 0;
val.forEach(({
status
}) => {
if (key === status)
count++;
})
result[key] = count
})
console.log("result", result)
推荐阅读
- python - 无法从 Pytorch 转换 MobiletNet_v1
- jpa - 如何处理 INSERT 并发问题,我在 glassfish 4.1 中使用 eclipselink jpa 和 mysql?
- r - RSelenium 在 Linux 下由 cron 运行时失败 - 为什么?
- html - 水平居中对齐引导程序连续 4 个表单
- java - 用于匹配 XML 字符串中的 CDATA 的正则表达式
- delphi - 如何使用 libcairo-2.dll?
- amazon-web-services - 如何用几个逻辑“或”编写 s3 条件存储桶策略?
- c# - 是什么 | 运算符在表达式主体属性中的含义?
- javascript - 从firebase中删除行后重新加载表
- php - 字符中时间值的 DataSeriesValues