-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
  • 159
  • 1
  • 2
  • 10

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
  • 66,969
  • 9
  • 47
  • 59
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
  • 47,092
  • 13
  • 101
  • 128