user545642
user545642

Reputation: 123

React - how to render content from JSON file?

How do I go about displaying the JSON file data properly in react?

Upvotes: 1

Views: 96

Answers (4)

Julian C
Julian C

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

Zohaib Ijaz
Zohaib Ijaz

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

James
James

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

PK07
PK07

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

Related Questions