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!
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!
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);
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));