-3

How can I access all values with the same key in an object array? Given the following data:

data = [{first_name: 'Peter', last_name: 'Smith', age: 45}, 
        {first_name: 'John', last_name: 'Miller', age: 21}];

Is there a easy way to get an array containing all first names, like first_names = ['Peter', 'John']?

I guess I'm asking a very frequently asked question, but I couldn't find a solution anywhere to answer it.

Kaniee
  • 111
  • 1
  • 10
  • Familiarize yourself on [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and use some of the [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods. – Sebastian Simon Oct 10 '19 at 14:32

1 Answers1

0

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

data = [{
    first_name: 'Peter',
    last_name: 'Smith',
    age: 45
  },
  {
    first_name: 'John',
    last_name: 'Miller',
    age: 21
  }
];

var first_names = data.map(ele => ele.first_name);

console.log(first_names)
nircraft
  • 8,242
  • 5
  • 30
  • 46