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?
bfvaretto: is that a big problem for me? How can I access names for peoples? Or if that's not possible: how can I make it an array instead of an object? Skip parseJSON - nalas 2012-04-05 22:10
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 };
var peopleArray = { people: parsedData };
But it makes no differences - I'm still not able to access my names by using: peopleArray.people[0].person1.name
Is still undefine - nalas 2012-04-05 22:12
peopleArray.people
? What's the value of peopleArray.people[0]
? What about peopleArray.people[0].person1
- Jordan Running 2012-04-06 15:39
console.log()
with Firebug or Web Inspector, not alert()
. - Jordan Running 2012-04-11 17:36