user8758206
user8758206

Reputation: 2191

Simple react error mapping through an array twice

I have a simple load of subs as follows:

subs: [
      {
        _id: '5f1c4b9423c9ea7f32b3877c',
        name: 'Test',
        email: '[email protected]',
        tag: 'indexForm',
        subDate: '25 July 2020',
        verified: false,
        authCode: 227,
      },
      {
        _id: '5f1c54257ceb10816a13d999',
        name: 'Jess',
        email: '[email protected]',
        tag: 'indexForm',
        subDate: '25 July 2020',
        verified: false,
        authCode: 641,
      },
      {
        _id: '5f1c646772c2318623fef058',
        name: 'Mike',
        email: '[email protected]',
        tag: 'indexForm',
        subDate: '25 July 2020',
        verified: false,
        authCode: 193,
      },
    ]

And I'm trying to just output some simple HTML such that a new row is created for each sub and then the key-value pairs are looped through. Here is the relevant part of the code that does not work:

{subs.map((sub) => (
   <div className='row'>
        Object.entries(sub).map(([key, value]) => (
           <div className={`user-col ${key}`}>{value}</div>
      ))
   </div>)
)}

Can anyone help determine why the error occurs? The error I'm getting is:

Line 36:39:  'key' is not defined    no-undef
Line 36:47:  'value' is not defined  no-undef

There's no error when the code is set to this although the HTML is wrong:

{subs.map((sub) =>
        Object.entries(sub).map(([key, value]) => (
          <div className='row'>
            <div className={`user-col ${key}`}>{value}</div>
          </div>
        ))
      )}

Any help would be greatly appreciated, thank you.

Upvotes: 0

Views: 87

Answers (2)

lissettdm
lissettdm

Reputation: 13078

You are missing {}:

     {
       subs.map((sub) => (
        <div className="row">
          {
            Object.entries(sub).map(([key, value]) => (
               <div className={`user-col ${key}`}>{value}</div>
            ))
          }

        </div>
      ))}

Upvotes: 1

Akino Archilles
Akino Archilles

Reputation: 104

map function returns 2 callback parameters which is key and value which is not wrapped inside an array.

so the code should look like this

{subs.map((sub) =>
        Object.entries(sub).map((value, key) => (
          <div className='row'>
            <div className={`user-col ${key}`}>{value}</div>
          </div>
        ))
      )}

Upvotes: 1

Related Questions