1

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

4 Answers 4

2

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>
  )
}
Sign up to request clarification or add additional context in comments.

4 Comments

I see. And I want to embed each of these names in a link, I can do that using Object.values() correct?
@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>)
@James Stay happy :)
@James Thank you very much.
2

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

FWIW when rendering lists you should provide a key, this code would flag a warning in the console.
1

Object.keys(data) gives ["1", "2" ....];

So you can loop through keys

Object.keys(data).forEach(function(key){
  console.log(data[key].name);
});

Comments

0

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

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.