1

I am trying to render a <li> which will print two to values in a single line. And then the third to value in the next <li>. So my object is like this.

let obj = [ 
{from : 'a1' , to : 'a7'},
{from : 'b1' , to : 'b7',
{from : 'c4' , to : 'c27'},
{from : 'a1' , to : 'a9'},
{from : 'j1' , to : 'a10'}
]

I want to output it like

1. a7 , b7
2. c27, a9
3.  a10

The obj is a react state. I am printing it using .map() function in js. But I want it to print in pairs of two. How can I achieve that.

moves.map((move, i) => {
                            return (
                                <li key={i}>{i}
                                    {move}
                                </li>
                            )
                        })

0

2 Answers 2

1

First, you have to iterate your obj variable pariwise.

const moves = [];

  for (let i = 0; i < obj.length; i += 2) {
    let move = obj[i].to;
    if (i + 1 < obj.length) {
      move += ", " + obj[i + 1].to;
    }
    moves.push(move);
  }

Then, you can simply iterate the newly created moves variable.

{moves.map((move, i) => {
        return (
          <p key={i}>
            {i + 1}. {move}
          </p>
        );
      })}

Note: You can use li instead of p tag.

Result:

enter image description here

Working demo at CodeSandbox.

Sign up to request clarification or add additional context in comments.

Comments

0

Should be able to do something like:

moves.map((move, i) => {
    return (
        <li key={i}>{i}
            {`move[i].to` + move[i+1] ? `, move[i+1].to` :''}
        </li>
    )
})

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.