1

I have a JSON object array like this:

people {
 {
    name: 'Alice',
    age: '25',
 },
 { 
    name: 'Bob',
    age: '34' 
 }
} 

I want to access the 'age' value of an person which has an 'name' value of 'Alice'. How do I do this in javascript? Something like (in pseudocode of what the logic is I'm aware this is not possible in javascript):

people['age'].value where name == 'Alice'

and the result would be: '25'. There seem to be a lot of related JSON questions, but none of the ones I found (as far as I could find) addressed this particular question

reectrix
  • 7,999
  • 20
  • 53
  • 81
  • Learn JavaScript. JSON is not a database engine. So you can not run queries like that. Do it using the `if` and comparison like you will do in any other language. – sarveshseri Feb 03 '15 at 19:50
  • The above was meant to be pseudo code than anything else; I'll clarify that in the question – reectrix Feb 03 '15 at 19:55

2 Answers2

3

You need to iterate over the object and compare name for what you are searching.

for(prop in people) {
    if(prop.name === "Alice") {
        console.log(prop.age);
    }
}

We need the age of Alice, we iterate over all objects and return object's age property value based on objects name property value.

Starmetal
  • 740
  • 6
  • 14
  • Please do not give direct answer ( code ) for such questions on StackOverFlow. – sarveshseri Feb 03 '15 at 19:51
  • 2
    Than, please don't post comments anymore on my answers, ok? – Starmetal Feb 03 '15 at 19:53
  • Well... Its Common behavior on StackOverFlow is to downvote any answers to such questions. I am telling you "free answers without effort"" is against the well being of StackOverFlow in long time. Also... I am advising you this... because you seem to be new here and seem to share a good purpose of helping fellow programmers. Best Wishes... keep on helping people. – sarveshseri Feb 03 '15 at 20:01
0

Since the people variable is an array of JSON objects, you cannot index them with the 'age' string. you could use the a simple for loop to loop through all the objects in the array and find the one where the name matches.

This piece of code is a function that returns the age of a person.

function get_age(people_array, name) {
    var length = people_array.length;

    for (var i = 0; i < length; i += 1) {
        if (people_array[i].name == name)
            return people_array[i].age;
    }
}
Thijs Riezebeek
  • 1,762
  • 1
  • 15
  • 22