我从如下所示的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
}
]
}
我想以这种形式创建ID数组ids = [1,2,3]
这是我的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 ]
请帮忙吗?
答案 0 :(得分:1)
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));
答案 1 :(得分:-1)
不清楚您到底想要什么,但是如果您想一次查看结果,请将打印移出循环:
for (var i = 0; i < companyid.length; i++){
ids.push(companyid[i].id)
}
console.log(ids)