Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs how to render pair-value of assoc array

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.

like image 230
Nevada Avatar asked May 04 '18 10:05

Nevada


People also ask

How do you create a key value pair array in React?

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).

How do you render each element in an array React?

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.

How do you access the array of objects in React?

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.

How do I map a key value in 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.


1 Answers

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>
like image 144
Ori Drori Avatar answered Sep 29 '22 17:09

Ori Drori