How to render pair-value of assoc array? I have assoc array:
let data = ["foo": 3, "bar": 5, "baz": 6];
and I need to render it in my component. I try something like this:
let content = data.map((value, index) => {
return (
<div key={index}}>
{index}: {value}
</div>
);
});
But it does not work.
You create your object (including its id property) and then you add it to the result array. You add the id property to the last object in your result array (since you talk about "newly created data" I am assuming it is always the last item).
To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.
To find an object in an array in React: Call the find() method on the array, passing it a function. The function should return an equality check on the relevant property. The find() method returns the first value in the array that satisfies the condition.
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.
If you have an object, and you want to iterate the keys and values of the object, use Object.entries()
to get an array of key/value pairs. Iterate the array of pairs with Array.map()
, and get the key (k
) and value (v
) using destructuring assignment:
const data = { foo: 3, bar: 5, baz: 6 };
const Example = ({ data }) =>
Object.entries(data).map(([k, v]) => (
<div key={k}>
{k}: {v}
</div>
));
ReactDOM.render(
<Example data={data} />,
demo
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="demo"></div>
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