Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> ))} 
like image 233
Sireini Avatar asked Nov 25 '16 11:11

Sireini


People also ask

Can you map through an object React?

To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.

How do I iterate a map object in React?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.

How do you pass an array of objects as a prop in React?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.

How do you render an object in an array in React?

To render an array of objects in React, we can use the array map method. const Item = (props) => { return <li>{props. message}</li>; }; const TodoList = () => { const todos = ["foo", "bar", "baz"]; return ( <ul> {todos. map((message) => ( <Item key={message} message={message} /> ))} </ul> ); };


1 Answers

When calling Object.keys it returns a array of the object's keys.

Object.keys({ test: '', test2: ''}) // ['test', 'test2']

When you call Array#map the function you pass will give you 2 arguments;

  1. the item in the array,
  2. the index of the item.

When you want to get the data, you need to use item (or in the example below keyName) instead of i

{Object.keys(subjects).map((keyName, i) => (     <li className="travelcompany-input" key={i}>         <span className="input-label">key: {i} Name: {subjects[keyName]}</span>     </li> ))} 
like image 132
TryingToImprove Avatar answered Sep 20 '22 12:09

TryingToImprove