2

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

2
  • 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. Commented Feb 3, 2015 at 19:50
  • The above was meant to be pseudo code than anything else; I'll clarify that in the question Commented Feb 3, 2015 at 19:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Please do not give direct answer ( code ) for such questions on StackOverFlow.
Than, please don't post comments anymore on my answers, ok?
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.
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;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.