Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!