Reputation: 29
I did finish my tutorial for reactjs and start making an webapp which stores data in a json.I was able to find my object from a json data and the object would represent something like this one:
var data={
name:<h1>Ram</h1>,
description:<p>I want to be a Developer</p>,
contact:<ul><li>66546464/li><li>66546464/li></ul>,
DOB:<h4>23.05.2017</h4>
}
I need to display in this way,but without using keys like
{data.name or data.DOB}.
Output should be like this:
<div>
<h1>Ram</h1>
<p>I want to be a Developer</p>
<ul><li>66546464/li><li>66546464/li></ul>
<h4>23.05.2017</h4>
</div>
Is it possible to display the values without knowing the key? If so,please do help me?
Critics are always welcome!
Upvotes: 3
Views: 2563
Reputation: 2081
You have to iterate over keys of the object and append it's value as a children of parent div. Please consider below code:
<div>
{Object.keys(data).map(key => data[key])}
</div>
Object.keys
will give you keys of object and map
function returns all the values of the key in a array format. It can be written in react JSX as shown in above code.
Upvotes: 1
Reputation: 15146
Here's how to do it in react.js
<div>
{Object.keys(data).map(key) => (
<span key={key}>
{data[key]}
</span>
)}
</div>
An explanation. Object.keys
takes all keys from your object, you map over them and for each one return a <span>
(note the key), and inside each span you take value from data by its key
Upvotes: 3
Reputation: 124
It makes more sense to store your data without the HTML tags (Storing with tags is bad practice, many frameworks/libraries will try to parse your special characters and cause you hassle down the road) Then you can access the raw data in your view with keys.
<h1>{data.name}</h1>
<p>{data.description}</p>
etc
If you're solidly against using keys, you may find this thread on pretty printing JSON data to be of help:
Pretty Printing JSON with React
Upvotes: 0