0

In my angularjs file I stringified my json result

console.log("details... "+JSON.stringify(response));

it is somewhat of this nature

{"data":{"success":true,"errorCode":0,"data":[{"id":1098,"surname":"Tony","firstname":"Wilson","othername":"","dob":"Jun 9, 2000 12:00:00 AM","gender":"MALE",

when I try to console for firstname I get a surprising outcome of undefined

console.log("firstname... "+ response.data.data.firstname) ;

please what could be wrong

Soviut
  • 83,904
  • 44
  • 175
  • 239
rocket
  • 223
  • 1
  • 2
  • 10

3 Answers3

1

The response.data.data is an array, that's what the square brackets are []. You must first access the item itself before accessing the firstname attribute on that item.

For example, to get the first item, you would do

console.log(response.data.data[0].firstname)
Soviut
  • 83,904
  • 44
  • 175
  • 239
1

Instead of:

console.log("firstname... "+ response.data.data.firstname) ;

Do:

console.log("firstname... "+ response.data.data[0].firstname) ;      

This happens because firstname is a key to an object which is inside an array named data.

BlackBeard
  • 9,544
  • 7
  • 47
  • 59
1

Your final data is an array. You have to specify index on that:

var response = {"data":{"success":true,"errorCode":0,"data":[{"id":1098,"surname":"Tony","firstname":"Wilson","othername":"","dob":"Jun 9, 2000 12:00:00 AM","gender":"MALE"}]}};
console.log("firstname... "+ response.data.data[0].firstname)
Mamun
  • 62,450
  • 9
  • 45
  • 52