0

I have a json object like below {"Title":"asb","Date":"2019","Other":"not important"} What is the correct way to read this object and render in <ul><li>?

Note I tried this by assigning this to a state and iterate state using map(), but it is not working.

12
  • It is depend on how you want to show your data Commented Mar 27, 2019 at 4:13
  • 1
    What do you mean, not working? Are you receiving an error? If so, what is error message? Commented Mar 27, 2019 at 4:14
  • Could you please be more specific ? Commented Mar 27, 2019 at 4:14
  • 1
    If this is not array of object then map wont work Commented Mar 27, 2019 at 4:16
  • Hi @brk then what is the best way to do this? one method I tried was, define a new array variable in render method , push the state to that new array and then reading the array object using map() method. Commented Mar 27, 2019 at 4:23

4 Answers 4

2

map can use with Array only, not Object. Use Object.entries to convert the object to an array first

const data = {"Title":"asb","Date":"2019","Other":"not important"}

const App = () => 
   <ul> 
     {
       Object.entries(data).map(([key, val]) => <li>{key}: {val}</li>)
     }
    </ul>
  
  
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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

Comments

2

It's an object, so map won't work. Iterate over Object.entries instead:

const object = {"Title":"asb","Date":"2019","Other":"not important"};
Object.entries(object).forEach(([key, value]) => document.getElementById("list").innerHTML += `<li>${key}: ${value}</li>`);
<ul id="list"></ul>

Comments

1

For object , you can use for loop , map is better use for array type

var data = {"Title":"asb","Date":"2019","Other":"not important"};

for(var i in data) {
  var htm = `<li>${i} : ${data[i]}</li>`;
  test.innerHTML += htm; 
}
<ul id=test></ul>

Comments

0

You can directly read see bellow example: case 1 :

var text  = { "Title": "asb", "Date": "2019", "Other": "not important" };
console.log(text.Date)

output :2019

case 2:

after convert and used

var s = '{"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}';

var obj = JSON.parse(s);

Comments

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.