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

Incorrect Array length and array element when saving a JSON object key

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

[
   {
     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 

数组中 getting/assigning 元素的错误方式?

您需要将 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;

试试这个,您的代码中有一个更正。您不是将 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
});
});