Question

eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:

$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data); }

I'm left with the array parsedData which looks like this:

[

{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}

]

I've placed those arrays in an array named

var peopleArray= { people: [ parsedData ] };

So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:

alert (peopleArray.people[0].person1.name);

Whiched returns:

Uncaught TypeError: Cannot read property 'name' of undefined

How can I access those attributes?

Was it helpful?

Solution

Apart from the typo ("namn") the problem is you're putting an array inside an array:

var peopleArray = { people: [ parsedData ] };

Since parsedData is an array then what you end up with is a structure like this:

// peopleArray
{ people :  [ [  { "person0" : ... }, ...  ] ]  }
//  oops -----^

See the problem? Since parsedData is a already an array the correct code would be:

var peopleArray = { people: parsedData };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top