I have a response like this:
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> ))}
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.
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.
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.
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> ); };
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;
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> ))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With