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.
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>
That is not a valid array. You need an object by the looks of it:
let data = {foo: 3, bar: 5, baz: 6};
You can then do:
let content = Object.keys(data).map(key => {
return (
<div key={key}>
{`${key}: ${data[key]}`}
</div>
);
});
Demo
class App extends React.Component { render() { let data = {foo: 3, bar: 5, baz: 6}; let content = Object.keys(data).map(key => { return ( <div key={key}> {`${key}: ${data[key]}`} </div> ); }); return <div>{content}</div>; } } ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div>
let data = [{"foo": 3}, {"bar": 5}, {"baz": 6}];
const content1 = data.map((value, index) => {
return (
<div key={index}>
{index}: {JSON.stringify(value)}
</div>
);
});
const content2 = data.map((value, index) => {
return (
<div key={index}>
{Object.keys(value)[0]}: {Object.values(value)[0]}
</div>
);
});
Output1
0: {"foo":3}
1: {"bar":5}
2: {"baz":6}
Output2
foo: 3
bar: 5
baz: 6
There are multiple ways to do it. one way could be
const data = { foo: 3, bar: 5, baz: 6 };
createList() {
let items=[];
for (const [index, value] of Object.entries(data)) {
items.push(<div key={index}}>{index}: {value}</div>)
}
return items;
}
render ( {this.createList();} )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.