-4
var students = [ {
    name:"Mary",
    age: 10
  }, 
 
  {
    name:"Barbara",
    age:11
  }, 
 
  {
    name:"David",
    age:12
  },
  
   {
    name:"Alex",
    age:11
  } ];
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ali
  • 11
  • 1
  • 1
    Does this answer your question? [Access object property in array of objects](https://stackoverflow.com/questions/19154224/access-object-property-in-array-of-objects) – empiric Jan 17 '22 at 14:11
  • [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – charlietfl Jan 17 '22 at 14:20

2 Answers2

0

You can use for..of syntax for iterating over the array elements. If the element has .name that you need, extract the .age:

function getAge(arr, name) {
    for (let s of students) {
        if (s.name == name) return s.age;
    }
}

Then you can use this function like this:

alert(getAge(students, 'Alex'));
Vlad Havriuk
  • 1,291
  • 17
  • 29
-1

Use Array.find to get the item in the array whose name property is "Alex", then get the item's age property:

var students=[{name:"Mary",age:10},{name:"Barbara",age:11},{name:"David",age:12},{name:"Alex",age:11}];

let res = students.find(e => e.name == "Alex").age
console.log(res)
Spectric
  • 30,714
  • 6
  • 20
  • 43