1

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"

2
  • 2
    people.forEach( x => console.log(Object.keys(x))) Commented Aug 24, 2018 at 9:55
  • thanks Satpal. But I see your method actually converts the properties on the object into array items. Commented Aug 24, 2018 at 10:11

2 Answers 2

1

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);
  }
});

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.