How do I go about displaying the JSON file data properly in react?
4 Answers
You effectively just want to pull the values of the object here, you can use Object.values in most modern browsers (unless you are using IE, which if you are I feel your pain)
Object.values(data).forEach(x => console.log(x.name)) To give you a working example in React:
import data from "./data.json" function renderLinks() { const records = Object.values(data); return ( <ul> {records.map((x, i) => <li key={i}><a href="#">{x.name}</a></li>)} </ul> ) } 4 Comments
user545642
I see. And I want to embed each of these names in a link, I can do that using Object.values() correct?
James
@DarrelGulseth yes you can, instead of
forEach you can simply map the result out e.g. Object.values(data).map(x => <a href="#">{x.name}</a>)Zohaib Ijaz
@James Stay happy :)
user545642
@James Thank you very much.
You can use Object.keys() and then map name property
import data from './data.json' // in render function, jsx {Object.keys(data).map(key => <span key={key}>{data[key].name}</span>)} 1 Comment
James
FWIW when rendering lists you should provide a
key, this code would flag a warning in the console.If you don't care about the order you can use Object.keys()
Object.keys(data).forEach((key) => { console.log(data[key].name); }); Otherwise, if you do care about the order, use a for loops and cast the integer as a string.
for(int i = 0; i < Object.size(data); i++){ console.log(data[i.toString()].name); }