I was Learning JavaScript and Stuck on this problem that if i had an array in which i had 2 objects like this -
const datas = [{name: "Father", age: 39}, {name: "Mother", age: 40}]
for (let data of datas){
console.log(data.age)
}
and the output when i print age - 39 40
How can i only print one value like only console.log() the value mother's age only
I tried To find it on google but no one could help if you could help it would mean a lot to me
First you should filter out the values, what you would like to get. Use filter method.
const datas = [{name: "Father", age: 39}, {name: "Mother", age: 40}]
datas.filter(data=>data.name === "Mother").forEach(data=>console.log(data));
Welcome to the JavaScript.
for (let data of datas)
This is actually called for..of loop in javascript. This is responsible for iterating through an array. So you will get every object by using the data variable.
Now as the for..of loop iterates through every element of an array so, if you need to take only one possible value from it, then you have to use if condition here.
In your case-
for (let data of datas) {
if (data.name === 'Mother') {
console.log(data.age);
}
}
Note that, if you only need the mother's age then you could also use the break keyword for getting out of the loop.
for (let data of datas) {
if (data.name === 'Mother') {
console.log(data.age);
break;
//--^^^^^^--------
}
}
Just add a condition, like that:
const datas = [{name: "Father", age: 39}, {name: "Mother", age: 40}]
for (let data of datas) {
if (data.name === "Mother") {
console.log(data.age)
}
}
or you can search through an array, for the necessary object, and then print its age property:
const mother = datas.find(obj => obj.name === "Mother");
console.log(mother.age);
Good luck!