-1

What I have is this:

const objArr = [
    {name: "John", id: 1}, 
    {name: "Marry", id: 2}, 
    {name: "Jack", id: 3}
  ] 

And I want this:

const names = [
    "John",
    "Marry",
    "Jack"
  ]

How? Thanks!

FatBoyGebajzla
  • 149
  • 2
  • 9

3 Answers3

2

Use Array.prototype.map() to return only the name property.

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

const objArr = [
    {name: "John", id: 1}, 
    {name: "Marry", id: 2}, 
    {name: "Jack", id: 3}
  ] 

const names = objArr.map(p => p.name);

console.log(names);
Mamun
  • 62,450
  • 9
  • 45
  • 52
1

here you go ;)

const names = objArr.map(person => person.name);
1

Just use map method in combination with destructuring by passing a callback provided function as argument.

const objArr = [{name: "John", id: 1}, {name: "Marry", id: 2}, {name: "Jack", id: 3}] 
console.log(objArr.map(({name}) => name));
Mihai Alexandru-Ionut
  • 44,345
  • 11
  • 88
  • 115