Skip to content

Get Names of Array of Objects without Looping

I have an array of country objects (countries) and I’m trying to get just an array of the String names, so from this example:enter image description here

Just: ['Canada', 'USA', ..] etc.

I’m trying to do this with

const getNames = (countries) =>{ Name }) => Name); 

but I can’t seem to get it. Any suggestions?


You’re quite close to getting it right; just remove (countries) => and you’re good to go.

const getNames ={ Name }) => Name); 

Alternatively, you can keep your code, which is a function. To get the names of the countries – coNames – call the function and pass countries as a parameter.

const getNames = (countries) =>{ Name }) => Name); 
const countries = [{id: ...., Name:.........}];
const coNames = getNames( countries );

Your code is equivalent to:

const getNames = function( countries ) {
    return{Name}) {
        return Name;