evan evan - 8 months ago 58
Javascript Question

Given the following array, how would I write an ES6 expression to return all the first names

const ducks = [
{ first: 'Stan', last: 'duck' },
{ first: 'Steve', last: 'duck' },
{ first: 'Kyle', last: 'duck' },
];


I've tried

const ducks = [
{ first: 'Stan', last: 'duck' },
{ first: 'Steve', last: 'duck' },
{ first: 'Kyle', last: 'duck' },
];

console.log(ducks, [3]);


This returns way too much:

[...] [3]
0: {first: "Stan", last: "duck"} 0: 3
1: {first: "Steve", last: "duck"} length: 1
2: {first: "Kyle", last: "duck"} __proto__: Array(0)
length: 3
__proto__: Array(0)


need it to return the names
"Stan"
,
"Steve"
, and
"Kyle"
only.

Answer Source

Use Array's map like the following:

 const ducks = [
 { first: 'Stan', last: 'duck' },
 { first: 'Steve', last: 'duck' },
 { first: 'Kyle', last: 'duck' },
 ];
 
 let res = ducks.map((item) => item.first);
 
 console.log(res);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download