首页 > 解决方案 > 如何从 JSON 数据创建数组而不重复值?

问题描述

我从如下所示的 API 中检索到 JSON:

{
    "status": "success",
    "response": [
        {
            "id": 1,
            "name": "SEA BUSES",
            "image": null
        },
        {
            "id": 2,
            "name": "BEN BUSES",
            "image": null
        },
        {
            "id": 3,
            "name": "CAPE BUSES",
            "image": null
        }
    ]
}

我想以这种形式 ids = [1,2,3] 创建一个 ID 数组

这是我的 JavaScript:

companyid = response.data.response
        var ids = [];
        for (var i = 0; i < companyid.length; i++){
           ids.push(companyid[i].id)
           console.log(ids)
        }

但输出不是我所期望的。它以这种方式显示:

[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]

请问有什么帮助吗?

标签: javascriptarraysjsonloopsfor-loop

解决方案


const json = {
  status: "success",
  response: [
    {
      id: 1,
      name: "SEA BUSES",
      image: null
    },
    {
      id: 2,
      name: "BEN BUSES",
      image: null
    },
    {
      id: 3,
      name: "CAPE BUSES",
      image: null
    }
  ]
};

console.log(json.response.map(item => item.id));

推荐阅读