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
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!!
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]}`);
})
})
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(","));
})
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