-1

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?

nalas
  • 85
  • 1
  • 12
  • 3
    Looks like you have a typo 'namn' ? – PseudoNinja Apr 05 '12 at 18:32
  • FYI, `peopleArray` is not an array, it's an object. – bfavaretto Apr 05 '12 at 18:36
  • the type was when I converted my variabel name to something more understandable. I've edited that out now. 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 Apr 05 '12 at 22:10

1 Answers1

3

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 };
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • I see. I've tried using your suggestion: 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 undefined – nalas Apr 05 '12 at 22:12
  • What's the value of `peopleArray.people`? What's the value of `peopleArray.people[0]`? What about `peopleArray.people[0].person1`? – Jordan Running Apr 06 '12 at 15:39
  • `peopleArray.people[0]` gives me `[object Object]`. – nalas Apr 11 '12 at 11:10
  • What does the object look like? (Use `console.log()` with Firebug or Web Inspector, not `alert()`.) – Jordan Running Apr 11 '12 at 17:36
  • Thx, that advice was very good. I didn't know that you could log-out the objects. With that knowledge I would have been able to solve this issue as it was just a matter of using e.g ['name'] instead of [0] – nalas May 16 '12 at 15:06