Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda