0

I have an API with a JSON Array of objects response like this

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

]

I am trying to save the values of person_id in an array but the values are not getting saved correctly and so the array length is coming incorrect.

Since I'm using Chakram, this is what I'm currently doing

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
});
});

I want to know why is this happening? Is

array_ids = api_response.body[i].person_id 

an incorrect way of getting/assigning elements in array?

demouser123
  • 4,108
  • 9
  • 50
  • 82

2 Answers2

2

You need to push ids into array

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

You can use Array.prototype.map()

let array_ids = api_response.body.map(obj => obj.person_id);
let count = array_ids.length;
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
2

Try this, there is a correction in your code. You're not pushing IDs into an array but you're assigning a new value of IDs every time.

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
});
});
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
  • You should explain what you changed and why. – Marie May 08 '18 at 18:20
  • 1
    @demouser123 In my opinion code-only answers aren't very helpful (giving a fish vs teaching to fish). Besides, I commented and planned on watching and removing my vote if it was edited. – Marie May 08 '18 at 18:27