Home > Software engineering >  Get Names of Array of Objects without Looping
Get Names of Array of Objects without Looping

Time:03-08

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) => countries.map(({ Name }) => Name); 

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

CodePudding user response:

Just this?

const getNames = countries.map(c => c.Name); 

CodePudding user response:

While topic says "without" looping, actually you can't. Map method also creates internal looping algorithm. So basically you can do something very simple and really efficient like standard for loop.

// Array of objects
const arr = [
  { id: 1, Name: "Canada", isSelected: false },
  { id: 2, Name: "USA", isSelected: false },
  { id: 3, Name: "India", isSelected: false }
];

// Function to get all params by name
const getAllParam = (arr, param, res = []) => {
  for(const e of arr) if(e[param]) res.push(e[param]);
  return res;
};

// Get all params with "Name" key
const res = getAllParam(arr, "Name");

// Test
console.log(res);

CodePudding user response:

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

const getNames = countries.map(({ 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) => countries.map(({ Name }) => Name); 
const countries = [{id: ...., Name:.........}];
const coNames = getNames( countries );

Your code is equivalent to:

const getNames = function( countries ) {
    return countries.map(function({Name}) {
        return Name;
    });
};
  • Related