Guide to utilizing nested map functions in JavaScript to retrieve specific elements

I have two arrays: one is a simple array, and the other is an array of objects.

Here are the arrays:-

arr1=["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"];
arr2=[ {
            "id": 21,
            "name": "johndoe",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="721a171e1e1d32151f131b1b5c111d1b">[email protected]</a>",
            "address": "test address",
            "voterid": "12131313",
            "mobile": "1211313",
            "aadhar": "213123131313",
            "pancard": "HYG579AA"
        },
        {
            "id": 24,
            "name": "johndoe3",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f49c9198989bc5b49399959d98da979b99">[email protected]</a>",
            "address": "test address",
            "voterid": "12111313",
            "mobile": "1211313",
            "aadhar": "112313131313",
            "pancard": "YHUIHU88"
        }];

I am trying to map arr2 within arr1 to retrieve the values using elements from arr1. Here is my attempt:

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

I want the items to be mapped like this:-

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

and so on...

However, I am unable to use the itx or arr1 after the dot notation, i.e., item.itx (itx is not being utilized).

Please let me know if there is any workaround for this issue.

Answer №1

In my opinion, this version may be easier to understand...

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

Answer №2

Separate your data manipulation logic from React component layout logic for better organization. Create a dedicated function called pick(obj, fields) -

const pick = (obj = {}, fields = []) =>
  fields.map(f => obj[f])

const arr1 = ["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"]
const arr2 = [{id: 21,name: "johndoe",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c64696060634c6b616d6560226f6361">[email protected]</a>",address: "test address",voterid: "12131313",mobile: "1211313",aadhar: "213123131313",pancard: "HYG579AA"},{id: 24,name: "johndoe3",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2aa...
  
console.log(arr2.map(obj => pick(obj, arr1)))

[
  [
    "213123131313",
    "test address",
    "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa2afa6a6a58aada7aba3a6e4a9a5a7">[email protected]</a>",
    "1211313",
    "johndoe",
    "HYG579AA",
    "12131313"
  ],
  [
    "112313131313",
    "test address",
    "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d25282121227c0d2a202c2421632e2220">[email protected]</a>",
    "1211313",
    "johndoe3",
    "YHUIHU88",
    "12111313"
  ]
]

You can now easily construct your table like this -

const rows = arr2.map(obj => pick(obj, arr1))
return <table>
  {rows.map(row =>
    <tr>{row.map(cell => <td>...</td>)}</tr>
  )}
</table>

Check out this complete example that you can test in your browser -

const pick = (obj = {}, fields = []) =>
  fields.map(f => obj[f])

function Table ({ rows, selector }) {
  return <table>
    {rows.map((row, key) =>
      <tr key={key}>
        {selector(row).map((cell, key) =>
          <td key={key}>{cell}</td>
        )}
      </tr>
    )}
  </table>
}

const arr1 = ["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"]
const arr2 = [{id: 21,name: "johndoe",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5ada0a9a9aa85a2a8a4aca9eba6aaa8">[email protected]</a>",address: "test address",voterid: "12131313",mobile: "1211313",aadhar: "213123131313",pancard: "HYG579AA"},{id: 24,name: "johndoe3",email...
ReactDOM.render(
  <Table rows={arr2} selector={x => pick(x, arr1)}/>,
  document.querySelector("main")
)
table { border: 1px solid black; }
td { border: 1px solid silver; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<main></main>

Here's another example with column headers included -

const pick = (obj = {}, fields = []) =>
  fields.map(f => obj[f])

function Table ({ rows, cols }) {
  return <table>
    <tr>
      {cols.map((col, key) =>
        <th key={key}>{col}</th>
      )}
    </tr>
    {rows.map((row, key) =>
      <tr key={key}>
        {pick(row, cols).map((cell, key) =>
          <td key={key}>{cell}</td>
        )}
      </tr>
    )}
  </table>
}

const arr1 = ["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"]
const arr2 = [{id: 21,name: "johndoe",email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1c9c4cdcdcee1c6ccc0c8cd8fc2cecc">[email protected]</a>",address: "test address",voterid: "12131313",mobile: "1211313",aadhar: "213123131313",pancard: "HYG579AA"},{id: 24,name: "johndoe3",email...
ReactDOM.render(
  <Table rows={arr2} cols={arr1} />,
  document.querySelector("main")
)
table { border: 1px solid black; }
th,td { border: 1px solid silver; }
th { font-weight: bold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<main></main>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the value of an HTML span tag during execution on a PHP Webdriver client and Selenium can be achieved

Currently working with the php webdriver client along with selnium Struggling to retrieve the value from the span tag showing Rs 350 <div class="fareBlock busDataBlock"> <div> <span class="fareStart">< ...

Tips for dynamically updating data with on.click functions in D3

Implementing pack layout with D3 v4 is my current task, and I am looking to adjust the circle sizes based on the values "funds" and "spend" in my csv file. The following code successfully scales the circles: rank(funds) rank(spend) However, the on.click ...

``Trouble with React Dropdown menu option selection"

I am encountering challenges with implementing a dropdown menu list for my react app. The issue at hand is that I have an API where one of the keys (key3) has values separated by commas that I wish to display in my dropdown list. The structure of the API ...

Fixing the error message "reached end of file while parsing" in programming

Currently, I am developing a program to identify and showcase the student with the highest GPA, alongside the student with the lowest GPA from a class containing four attributes (first name, last name, age, GPA). Despite receiving a "build successful" mes ...

Creating dynamic and asynchronous JSON structures with JavaScript

Struggling with async JavaScript here. I've got a function called within a jQuery AJAX function, and it looks like there are more async method calls in that function. Currently stuck in this situation. Here's the code snippet triggered by the jQ ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

Is there a way to determine the remaining time or percentage until document.ready is reached?

My usual approach is to display a loading animation like this: $('#load').show(); $(document).ready(function(){ $('#load').hide(); }); where the <div id="load"> contains just an animated gif. However, I've been conside ...

Attempting to utilize a for loop in JavaScript to condense code, however encountering a "not defined" error

I'm relatively new to working with javascript and currently attempting to enhance the following code snippet (which has been tested and is functioning correctly): // snail 1 // var s1 = document.createElement("div"); s1.id = snail1.id; s1.className = ...

Is there a method available to retrieve the video duration prior to uploading it?

Is there a method to restrict users from uploading videos longer than 30 seconds? ...

Steps for removing a p5.js instance once three.js assets have finished loading

I am trying to implement a preload animation using a p5 sketch while loading a three.js gltf file onto my webpage. The idea is to have the p5 animation play while the heavy gltf file loads in the background. However, I am facing issues with triggering the ...

What is the best way to retrieve the overall error status from the Material UI DataGrid?

I am currently utilizing the Material UI DataGrid element to display information from an EXCEL file. Each Excel document consists of numerous column titles with specific types assigned to them. As an example: const columns = [ { "field&quo ...

Exploring the capabilities of ngWebDriver to interact with a dynamic ng-repeat through Selenium

I'm currently in the process of automating a web interface that contains frames built with Angular JS. I'm specifically looking to access an ng-repeat located within dynamic columns. Here's a snippet of the DOM structure I'm dealing wi ...

Utilize JavaScript to randomly choose images as background tiles in HTML

Currently, I am in the process of developing a game using HTML/CSS/JavaScript. My background is currently set to a single image (100px / 100px) being repeated vertically and horizontally to tile across the entire page body; CSS: body { background-ima ...

Transitionend event fails to trigger when Chrome tab is not in focus

$("#element").addClass("myclass").on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function (e) { $("#element").addClass('text-success'); $("#element2").addClass('myclass2'); setTimeout(function () { ...

The result of combining two JavaScript variables

When I multiply a variable by 2 and assign the value to another variable, why do I get 0? My goal is to toggle the visibility of blocks every time a button is pressed. Oddly enough, it works when I use count++ * 2. For code reference, please refer below: ...

Showing a div with seamless elegance

XHTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>example</title> </head> <style > body{ background: black; } ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Animating a div to glide back and forth in Javascript - with a quirky little 'ear' twist

I am looking to implement a feature that allows me to slide a div left and right. I have successfully achieved this using a button click, as suggested in other posts. However, What I would like to do now is add a small floating 'ear' icon that ...

The Date object and ISO date object yield varying results in their date displays

I am faced with the task of extracting a date value, converting it to an ISODate, and then searching a mongoDB collection that contains an object with a date value. The query is designed to compare the date of an event and determine if it falls on a weeken ...

Clicking on a link in HTML with the onclick event

I am looking to create a button that will direct me to a different page. Here is the code snippet I have: <div align="right" ><input type="submit" id="logout" onclick="location.href='/login?dis=yes'" value="Sign Out" ></div>& ...