Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
if i had an array in which i had 2 objects both had same key name and only want to print the value of one key

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

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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));

about 4 years ago · Santiago Trujillo Denunciar

0

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;
//--^^^^^^--------
  }
}
about 4 years ago · Santiago Trujillo Denunciar

0

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!

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda