简体   繁体   中英

React - how to render content from JSON file?

如何在反应中正确显示 JSON 文件数据?

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

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

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

So you can loop through keys

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM