Home > Software design >  What is the React JS equivalent of map function for objects?
What is the React JS equivalent of map function for objects?

Time:09-30

I am new to React, so please bear with me as I unveil my question. I am trying to handle API calls so that I can display the returned JSON files on HTML tables. So far I have been using the map function in order to properly assign keys and values to the table cells.

One thing I noticed almost right away, which the internet search could not help me with, was that the map function was useful and functional to me so long as the returned data of a JSON file were inside square brackets ..[].., possibly leading to them being items inside a table. See below:

[
    {
        "id_1": 0,
        "id_2": 1,
        "id_3": 30,
        "id_4": 9,
        "id_5": 0,
        "id_6": "Marty",
        "id_7": "111-111-1111",
        "location": "Algiers",
        "id_0": 0
    }
]

Once I stumbled upon a JSON file, the data of which were not inside square brackets but just regular curly brackets ..{}.. it appeared that the map function no longer made sense. See below:

{
    "id_1": 1,
    "whatever_id": 1,
    "whatever_name": "Blah",
    "id_0": 0
}

Hence my question of which function instead of .map I can use to render such a JSON file inside an HTML table.

I would like to give notice to the fact that once the react app compiles and localhost:**** fires up, data are not shown in the form of a table. However, I can see that the API was successfully called upon by inspecting the app and hitting the network tab to check the contents of the returned call. At this point I am giving a sample of what the table code looks like:

<table className='in-line'>
        <thead>
          {(items.length > 0) ? items.map((item, index) => {
            return (
              <Fragment key={index}>
                <tr><th>Blah blah 1</th><td>{item.id_1}</td></tr>
                <tr><th>Blah blah 2</th><td>{item.id_2.nameless_id}</td></tr>
                <tr><th>Name</th><td>{item.id_2.name}</td></tr>
                <tr><th>Blah blah 3</th><td>{item.id_2.wired_id}</td></tr>
                <tr><th>Update</th><td>{item.update}</td></tr>
                <tr><th>Record</th><td>{item.record}</td></tr>
              </Fragment>
            );
          }) : <tr><td colSpan='5'>Data Loading...</td></tr>}
        </thead>
        <tbody>
        </tbody>
      </table>

The <th> and <td> contents are random just to indicate how the table is formed. In its current state it can render a JSON file that is within square brackets, but not a JSON file within curly brackets only.

I hope this post has not been very off-putting and the question has been clearly stated. I would like to thank everyone that takes a minute to ponder over this! Kind regards!

CodePudding user response:

[] is an array {} is an object

map belongs to arrays. You can take a look at object prototype if you want to "convert" them into arrays. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

As an example:

if you want to get all the values and don't care about the key :

Object.values(items).map(value => { ... })

if you only want the keys and don't care about the value :

Object.keys(items).map(key => { ... })

if you want to need both key and value

Object.entries(items).map(([key, value]) => {...})

CodePudding user response:

JSON is a string-based data interchange format.

To map over each property of the objects represented in your JSON, first you need to parse the JSON string into an object using JSON.parse. Your JSON parses into an array of objects.

In order to use Array#map (read this as 'array dot prototype dot map') on each object in your array, you need to create an array from the properties on each object. Object.entries or Object.keys or Object.values will help with this.

const json = `
[{ "id": 1,
   "name": "cat" }, 
 { "id": 2,
  "name": "dog" },
 { "id": 3,
  "name": "rabbit" }]`

for(const o of JSON.parse(json))
  Object.entries(o).map(([key, value]) => console.log(`key: ${key}, value: ${value}`))

  • Related