[javascript] ReactJS map through Object

I have a response like this:

enter image description here

I want to display the name of each object inside this HTML:

{subjects.map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">{ item.name }</span>
  </li>
))}   

But it throws an error of subjects.map is not a function.

First, I have to define the keys of the objects where it creates an array of keys, where I want to loop through and show the subject.names.

What I also tried is this:

{Object.keys(subjects).map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">key: {i} Name: {subjects[i]}</span>
  </li>
))}

This question is related to javascript reactjs jsx

The answer is


You get this error because your variable subjects is an Object not Array, you can use map() only for Array.

In case of mapping object you can do this:

{ 
    Object.keys(subjects).map((item, i) => (
        <li className="travelcompany-input" key={i}>
            <span className="input-label">{ subjects[item].name }</span>
        </li>
    ))
}  

I use the below Object.entries to easily output the key and the value:

{Object.entries(someObject).map(([key, val], i) => (
    <p key={i}>
        {key}: {val}
    </p>
))}

Also you can use Lodash to direct convert object to array:

_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]

In your case:

_.toArray(subjects).map((subject, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">Name: {subject[name]}</span>
    </li>
))}

I am not sure why Aleksey Potapov marked the answer for deletion but it did solve my problem. Using Object.keys(subjects).map gave me an array of strings containing the name of each object, while Object.entries(subjects).map gave me an array with all data inside witch it's what I wanted being able to do this:

const dataInfected = Object.entries(dataDay).map((day, i) => {
    console.log(day[1].confirmed);
});

I hope it helps the owner of the post or someone else passing by.


Map over the keys of the object using Object.keys():

{Object.keys(yourObject).map(function(key) {
  return <div>Key: {key}, Value: {yourObject[key]}</div>;
})}

Do you get an error when you try to map through the object keys, or does it throw something else.

Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input" key={i}>
     <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>
))}

You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.


Use Object.entries() function.

Object.entries(object) return:

[
    [key, value],
    [key, value],
    ...
]

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

{Object.entries(subjects).map(([key, subject], i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subject.name}</span>
    </li>
))}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to jsx

TypeScript and React - children type? How to use componentWillMount() in React Hooks? expected assignment or function call: no-unused-expressions ReactJS You should not use <Link> outside a <Router> ReactJS - .JS vs .JSX React: Expected an assignment or function call and instead saw an expression React-Native Button style not work ReactJs: What should the PropTypes be for this.props.children? ReactJS map through Object Console logging for react?