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

140
Visualizações
Print array key without value

Good afternoon, I am doing a little exercise and I have a problem, I will expose you:

var elements = [
     { 
        name: 'Banana',
        price: 200,
        qty: 31,
        imported: true,
        size: [12, 40, 60],
        type: null
    },
    {
        name: 'Pomelo',
        price: 55,
        qty: 325,
        imported: false,
        size: [5, 50, 55, 79],
        type: '-'
    }
];

Get a result like this on the console

enter image description here

for(let i=0; i<elements.length;i++)
{
    console.log("***" + elements[i].name + "***");
    console.log("size:"+ elements[i].size);
}

I have this code and it works, but in the second console.log, how can I get the key out of the array without having to type "size" manually?

Thanks!!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Object.keys to access keys of an object.

var elements = [
  { name: 'Banana', price: 200, qty: 31, imported: true, size: [12, 40, 60], type: null },
  { name: 'Pomelo', price: 55, qty: 325, imported: false, size: [5, 50, 55, 79], type: '-' }
];

elements.forEach((element) => {
  Object.keys(element).forEach((key) => {
    console.log(`Key: ${key}`);
    console.log(`Value: ${element[key]}`);
  })
})

about 4 years ago · Juan Pablo Isaza Relatório

0

Is this useful for you

var elements = [
 { 
    name: 'Banana',
    price: 200,
    qty: 31,
    imported: true,
    size: [12, 40, 60],
    type: null
},
{
    name: 'Pomelo',
    price: 55,
    qty: 325,
    imported: false,
    size: [5, 50, 55, 79],
    type: '-'
}]

elements.forEach(x => {
  console.log("***" + x.name + "***");
  console.log("size :", x.size.join(","));
})

about 4 years ago · Juan Pablo Isaza Relatório

0

You can get the size key like this:

for(let i=0; i<elements.length;i++)
{
    console.log("***" + elements[i].name + "***");
    console.log(Object.keys(elements)[4] + ":" + elements[i].size);
}

But this will work when the size key is always on the 4th index as it is in your elements object

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