0

I am mapping out an array in one of my React components.

Is it possible to replace values when using map to write out each member of an array?

For example, if I have this array:

{ rowInfo.value.map(
      weaponIds => (<span>{weaponIds}</span>)
) }

that writes out:

<span> 1 </span>
<span> 3 </span>
<span> 4 </span>
<span> 8 </span>

Can I change it so that, instead of printing out the Id, it prints out the name of the weapon associated with that ID?

so :

<span> Pistol </span>
<span> Hunting Rifle </span>
<span> Machete </span>
<span> Machine Gun </span>

Note that the names do not exist in the API.

So I would somehow have to assign it so that 1 = Pistol, 2 = Dagger, 3 = Hunting Rifle, etc...

I tried writing out like this:

{ rowInfo.value.map(
      weaponIds => (<span>{weaponIds => (1 = Pistol), (2 = Dagger) etc... }</span>)
) }

But that throws a bunch of errors and my page no longer loads at all.

Thanks for any helps! :)

2
  • 2
    You could make an object and look the values up in them, weaponIds => ({1: 'Pistol', 2: 'Dagger', ...}[weaponIds]) or something of that nature Commented Apr 15, 2020 at 18:30
  • 2
    Why don't you make an object like const weapons = {1: 'Pistol', 2: 'Dagger'}; and use this as weapons[weaponIds] Commented Apr 15, 2020 at 18:31

2 Answers 2

2

Create an object with all keys and value

const obj = {
  1: 'Pistol',
  2: 'Dagger',
  //...
}

Then, use:

{ 
  rowInfo.value.map(
    weaponIds => (<span>{obj[weaponIds]}</span>) 
  ) 
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi thanks but would this make it so whenever it finds a 1, it prints out 'Pistol', or a 2, it prints out 'Dagger' instead of printing out 1 and 2? Thx
obj[1] will return "Pistol" or any other value which corresponds to key - 1
will this work in javascript for React? Or do I need something else?
When I try this, is says 'Pistol' is not defined or 'Dagger' is not defined. Do I need to create something new for each? Thanks
just updated, it should be const obj = { 1: 'Pistol', 2: 'Dagger' } 'Pistol' or 'Dagger' is string
1

Have you tried using an Enum?

enum Weapons {
   Pistol = 1,
   Dagger,
   'Machine Gun',
   ...
}

{ rowInfo.value.map(
  weaponIds => (<span>{Weapons[weaponIds]}</span>)
) }

4 Comments

Hi noo I haven't, I'm not sure how this would work in React? thanks
I just saw you are using javascript, not typescript. javascript doesnt support enums out of the box, sorry :(.
oh ok Im sorry I forgot to mention that
actually you did in the tags

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.