var students = [ {
name:"Mary",
age: 10
},
{
name:"Barbara",
age:11
},
{
name:"David",
age:12
},
{
name:"Alex",
age:11
} ];
CodePudding user response:
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'));
CodePudding user response:
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)
