1

I have an array of objects like this:

[
  {
    id: 1,
    name: 'Bill',
    age: 42
  },
  {
    id: 2,
    name: 'Jack',
    age: 37
  }
]

I know how to copy all of it to the new array by using array spreads ... in es6 instead of slice()

const newArray = [...oldArray];

I just want to extract the name using the method below:

const newArray = [];
for (i = 0; i < oldArray.length; i++) {
    newArray.push(oldArray[i].name);
}

Is there a better method to do this in es6?

Hien Tran
  • 1,443
  • 2
  • 12
  • 19

1 Answers1

3

Use Array.prototype.map():

let people = 
[
  {
    id: 1,
    name: 'Bill',
    age: 42
  },
  {
    id: 2,
    name: 'Jack',
    age: 37
  }
]

let names = people.map(person => person.name)

jsbin.

agconti
  • 17,780
  • 15
  • 80
  • 114