Reputation: 123
How do I go about displaying the JSON file data properly in react?
Upvotes: 1
Views: 96
Reputation: 1
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);
}
Upvotes: 0
Reputation: 22925
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>)}
Upvotes: 2
Reputation: 82136
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>
)
}
Upvotes: 2
Reputation: 61
Object.keys(data) gives ["1", "2" ....];
So you can loop through keys
Object.keys(data).forEach(function(key){
console.log(data[key].name);
});
Upvotes: 1