我从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数组,格式为id=[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 ]
请帮忙吗?
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));
不清楚你到底想要什么,但如果你想看一次结果,请将打印从循环中移出:
for (var i = 0; i < companyid.length; i++){
ids.push(companyid[i].id)
}
console.log(ids)