Kevin
Kevin

Reputation: 27

Reading Json object using map()

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.

Upvotes: 0

Views: 88

Answers (4)

Paresh Parmar
Paresh Parmar

Reputation: 11

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);

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

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>

Upvotes: 2

tam.dangc
tam.dangc

Reputation: 2042

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>

Upvotes: 2

デビット
デビット

Reputation: 129

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>

Upvotes: 1

Related Questions