2

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!

  • Possible duplicate of [How to get all properties values of a Javascript Object (without knowing the keys)?](https://stackoverflow.com/questions/7306669/how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key) – Guillaume Georges Jun 19 '18 at 16:36
  • Thank you for your answer!Can you please show me with an example in react? That would be really helpful @GuillaumeGeorges – ramakrishnar Jun 19 '18 at 16:43

3 Answers3

2

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

Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
1

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.

Hriday Modi
  • 2,001
  • 15
  • 22
0

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

rborum
  • 124
  • 1
  • 11