Search code examples
javascriptarraysjsxarray-map

How to use map within a map in javascript to access particular element


I have two array one is a simple array and the another is the array of objects.

Here is the arrays:-

arr1=["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"];
arr2=[ {
            "id": 21,
            "name": "johndoe",
            "email": "hello@gmail.com",
            "address": "test address",
            "voterid": "12131313",
            "mobile": "1211313",
            "aadhar": "213123131313",
            "pancard": "HYG579AA"
        },
        {
            "id": 24,
            "name": "johndoe3",
            "email": "hello1@gmail.com",
            "address": "test address",
            "voterid": "12111313",
            "mobile": "1211313",
            "aadhar": "112313131313",
            "pancard": "YHUIHU88"
        }];

I want to map arr2 within arr1 to get the value using the first arr1. This is what I tried :

 {arr2.map((item) => {
              return (
                <Tr key={item.id}>
                  {arr1.map((itx) => {
                    return <Td>{item.itx}</Td>;
 })}
}

I want the item to be mapped like this:-

item.aadhar
item.address
item.email
item.mobile

and so on...

but I am unable to use the itx or arr1 after dot i.e item.itx (itx is not being used).

Do let me know if there is any way to do this.


Solution

  • Maybe this is more readable...

    arr2.map(row => {
      return (
        <tr key={row.id}>
          {
            arr1.map(item => {
              return (
                <td key={`${row.id}_${item}`}>
                  {row[item]}
                </td>
              )
            })
          }
        </tr>
      )
    });