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
  • 88,194
  • 49
  • 192
  • 260
rocket
  • 253
  • 1
  • 2
  • 13

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
  • 88,194
  • 49
  • 192
  • 260
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
  • 10,246
  • 7
  • 52
  • 62
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
  • 66,969
  • 9
  • 47
  • 59