Return all values of a given property in a Javascript object array

Asked

Viewed 35 times

0

I have a certain array

var people = [
  {
    name: 'Leandro',
    age: 36
  },
  {
    name: 'Joaquim',
    age: 29
  },
  {
    name: 'Maria',
    age: 25
  }
]

If I want to return the name property at the first position I do the following

console.log(people[0].name)

How do I return all the names contained in the name property? The desired result is this:

Leandro, Joaquim, Maria

1 answer

3


You create a new array using the method map of the original array:

var people = [
  {
    name: 'Leandro',
    age: 36
  },
  {
    name: 'Joaquim',
    age: 29
  },
  {
    name: 'Maria',
    age: 25
  }
];
var names = people.map(person => person.name);
console.log(names);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.