保存 JSON 对象键时数组长度和数组元素不正确



我有一个带有像这样的 JSON 对象数组响应的 API

[
{
person_id:"12212",
person_name:"some name",
deptt : "dept-1"
},
{ 
person_id: "12211",
person_name: "some name 2"
deptt : "dept-2"
},
]

我正在尝试将person_id的值保存在数组中,但这些值未正确保存,因此数组长度不正确。

由于我正在使用Chakram,这就是我目前正在做的事情

it('gets person id in array',()=>{
let array_ids =[];
let count=0;
return response.then((api_response)=>{
for(var i=1;i<api_response.body.length;i++){
//this is correctly printing the person id of response
console.log('Person ids are ==>'+api_response.body[i].person_id);
count++;
//this is not working
array_ids = api_response.body[i].person_id;
}
console.log('Count is '+count) //prints correct number
console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});

我想知道为什么会这样?是

array_ids = api_response.body[i].person_id 

在数组中获取/分配元素的错误方法?

试试这个,你的代码中有一个更正。您不会将 ID 推送到数组中,而是每次都分配一个新的 ID 值。

it('gets person id in array',()=>{
let array_ids =[];
let count=0;
return response.then((api_response)=>{
for(var i=1;i<api_response.body.length;i++){
//this is correctly printing the person id of response
console.log('Person ids are ==>'+api_response.body[i].person_id);
count++;
//this is not working
array_ids.push(api_response.body[i].person_id); //update
}
console.log('Count is '+count) //prints correct number
console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});

您需要将 id 推送到数组中

array_ids.push(api_response.body[i].person_id);

您可以使用Array.prototype.map()

let array_ids = api_response.body.map(obj => obj.person_id);
let count = array_ids.length;

最新更新