How can I loop over this array of objects and output the key of the object
var people = [
{ name: "jon", age: 42 },
{ name: "mary", age: 32 }
]
so the above would return:
// "name" "age", "name" "age"
asked Aug 24, 2018 at 9:54
swisstony
1,7153 gold badges18 silver badges29 bronze badges
2 Answers 2
You can iterate over the array and use the for ... in loop to output the keys.
var people = [
{ name: "jon", age: 42 },
{ name: "mary", age: 32 }
]
people.forEach(function(element) {
for (let key in element) {
console.log(key);
}
});
answered Aug 24, 2018 at 9:56
user10243107
Sign up to request clarification or add additional context in comments.
Comments
Use Object.keys() to extract keys from an object.
var people = [
{ name: "jon", age: 42 },
{ name: "mary", age: 32 }
]
console.log(people.map(o => Object.keys(o).join(" ")).join(", "));
Another example to match the exact output:
var people = [{
name: "jon",
age: 42
}, {
name: "mary",
age: 32
}]
var result = people.map(o => Object.keys(o).map(string => `"${string}"`).join(' ')).join(', ');
console.log(result);
answered Aug 24, 2018 at 9:58
Arup Rakshit
119k30 gold badges270 silver badges328 bronze badges
Comments
lang-js
people.forEach( x => console.log(Object.keys(x)))