Rami Salim
Rami Salim

Reputation: 192

Mapping an object of array in Reactjs

I have an object each key of the object has an array value

const correctionsWords  = {
"word": [ "1" , "2"] ,
"word2": ["20" ,"22" ] 
};

I did map through each key by using the following code

let correctionList =  Object.keys(correctionsWords).map(  (key)  => {
        return (
          <div>
              {
                  //console.log( 'After Mapping ' , correctionsWords[key]) [1,2,3]
                   <ul>
                     <li>{key} { /* word  */}
                      <ul> 
                        <li>{correctionsWords[key]}</li>
                      </ul>
                     </li>  
                     </ul>
              } 
          </div> 
        ); });

the result is * key: word * value: 1 2 How can I list the values of the array?

Upvotes: 0

Views: 84

Answers (2)

devserkan
devserkan

Reputation: 17648

Map again each array element:

<ul>
  {correctionsWords[key].map(el => (
    <li key={el}>{el}</li>
  ))}
</ul>

I've used a key as the element here. If the elements are not unique better use another key. Also, you need another key for your object mapping in the topmost div:

return (
    <div key={key}>
    ...

Upvotes: 1

Ben Steward
Ben Steward

Reputation: 2417

I think what you’re looking for is to replace that innermost li with:

{
  correctionsWords[key].map(value => <li>{value}</li>)
}

Upvotes: 1

Related Questions