javascript - 如何从 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 ]
请问有什么帮助吗?
解决方案
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));
推荐阅读
- jsp - 如何根据用户角色显示元素?
- mysql - MySQL 分组给出 4 行而不是 1
- python - 如何使用 python 请求库发送此请求
- python - Kivy '崩溃' 没有错误消息 ['aborted (disconnected)']
- python - 了解python字典的顺序
- java - 压缩解压字符串得到的数据与原始压缩数据不一致
- python - 获取 Twisted 服务器的 IP 地址
- node.js - 如何在 AWS EC2 中为多个开发人员正确安装 nvm/node/npm?
- python - MySQL 数据为 varchar 255 和字符串截断
- python - BulkIndexError: ('500 document(s) failed to index.',使用 Python + Elastic Searc