3

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!

2

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks for the help!
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

1 Comment

Thanks for the headsup! I'll look into it @Ryan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.