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

95
Visualizações
Javascript Objects - Check for and loop through arrays in object

I am trying to loop through an object literal and if a property is an array, I want to loop through that as well. The friends property of this object is an array, how would I test to see if it's iterable, then loop through it?

Thanks in advance,

  firstName: 'Jonas',
  lastName: 'Schmedtmann',
  age: 2037 - 1991,
  job: 'teacher',
  friends: ['Michael', 'Peter', 'Steven'],
};
const myObj = Object.entries(jonas);
for (const [key, val] of myObj) {
   //Some conditional statement here testing for an interable
   //Then loop through it to the console.
  console.log(key, val);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

All arrays are instance of the Array class in Javascript so you can use var instanceof Array which returns a boolean to check if an element is an array or not, then iterate through it as you wish

const obj = {
    firstName: 'Jonas',
    lastName: 'Schmedtmann',
    age: 2037 - 1991,
    job: 'teacher',
    friends: ['Michael', 'Peter', 'Steven'],
};
const myObj = Object.entries(obj);
for (const [key, val] of myObj) {
    //Some conditional statement here testing for an interable
    //Then loop through it to the console.
    if (val instanceof Array) {
        console.log('element is an array, printing now')
        print(val);
    } else 
        console.log(key, val);
}

function print(ar) {
    ar.forEach(x => console.log(x));
}

about 4 years ago · Juan Pablo Isaza 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