首页 > 解决方案 > 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"
}

标签: javascript

解决方案


如果您的意图只是计算每个索引的数组长度,那么您就可以了,

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)


推荐阅读