0

I've been learning how to work with .map() function as it used pretty often for dealing with API results,

However I have a few questions that I wasn't able to solve on my own -

<div className="boxer">

    {users.map((user) => (
        <div className="scoreBoxx" key={user.id} id={user.id}>
            <h2 className="CardTitle">{user.videogame.name}</h2>
        {user.opponents.map((sub) => 
            <p key={sub.id} className={sub.acronym}>
                <b>Team :</b> {sub.opponent.name}  
            </p>
        )}

</div>

This is printing data out for me like this -

Team : ZdrastvyteTimur
Team : xStiKz

What I'm trying to achieve is:

Team : ZdrastvyteTimur - xStiKz

This is what my data looks like:

I apologise if this question has been asked prior, I have tried searching but wasn't able to find anything similar,

I have also tried fixing my problem by using slice() but haven't been able to work it out yet,

5
  • You might want to consider moving your (inconsistently indented...) React JSX to separate functions to keep your code readable. Commented Mar 30, 2022 at 13:54
  • Your posted JSX doesn't have the closing )} for the users.map callback, only the user.oppoonents.map callback. Commented Mar 30, 2022 at 13:56
  • Please post any code/data as text, not screenshot. Commented Mar 30, 2022 at 13:58
  • Also, "ZdrastvyteTimur" and "xStiKz" doesn't appear in the JSON you've posted. Commented Mar 30, 2022 at 14:00
  • @Dai Hey, thank you for the edit and support - I know about the closing )} tags but as it wasn't important piece of code information I didn't include everything, I'm not getting any errors as I mentioned - Just trying to experiment and learn more about array manipulation, Also regarding the JSON data - Its a live API so it keeps changing, 'xStiKz' was just an example for explain my question, Sorry about any issues this may have caused. Commented Mar 30, 2022 at 14:05

2 Answers 2

1

You could use reduce instead of map.

For example :

<b>Team : </b> {user.opponents.reduce((previous, current) => previous + ' - ' + current.opponent.name, '')}
Sign up to request clarification or add additional context in comments.

4 Comments

Repetitive string concatenation using + is potentially expensive in JavaScript, consider using join instead.
@Dai Yes, if you combine it with map.
user.opponents.map( o => o.opponent.name ).join( " - " )
@Rukka that did it, I had no idea it was this simple, Many thanks for your time and effort, Really appreciate it a lot.
0

Maybe try this :

<b>Team :</b> {user.opponents.map((sub) => 
              <span key={sub.id} className={sub.acronym}>
          {sub.opponent.name}  
           </span>
        
            )}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.