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,373
  • 2
  • 11
  • 18

1 Answers1

2

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
  • 16,911
  • 15
  • 76
  • 112