0

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?

8
  • What is the result when you run your code? Are you wanting it to be a function? Commented Mar 7, 2022 at 20:56
  • What do you mean 'I can't seem to get it', did you get a result different from from what you expected? What was it? Commented Mar 7, 2022 at 20:56
  • 2
    How do you call the function getNames? Please replace the image with a text-based minimal reproducible example Commented Mar 7, 2022 at 20:56
  • That function should work. countryNames = getNames(countries) Commented Mar 7, 2022 at 20:57
  • 1
    @user1599011 - the dummy param in the op is being assigned with (the relatively new) destructuring assignment. ({ Name }) plucks the name from the passed object Commented Mar 7, 2022 at 21:03

3 Answers 3

2

Just this?

const getNames = countries.map(c => c.Name); 
Sign up to request clarification or add additional context in comments.

1 Comment

Agree, but I don't see how this will work when the OP's equivalent doesn't
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.