访问嵌套的 JSON 对象以读入 React 中的 table

Accessing a nested JSON object to read into a table in React

我有一个 JSON object,我正在尝试使用 React 将其解析为 table,但是我在使用 .map() 尝试为每个对象创建一行时遇到了问题课程代码 nametransferable_creditstransferable_credits -> institutiontransferable_credits -> nameurl 的独特组合。我似乎无法弄清楚如何在每个 JSON 根键值对中获取嵌套数组的键值。

到目前为止我的 React 组件:

import data from './data.json'

const Home = () => {

    return ( 
        <div className="home">
            <table>
                <thead>
                    <tr>
                        <th>Course Code</th>
                        <th>Vendor Institution</th>
                        <th>Vendor Course</th>
                    </tr>
                </thead>
            <tbody>
                {Object.keys(data).map(function(key, index) {
                    return (
                        <tr key={index}>
                            <td>{key}</td>
                            {Object.keys(data[key].transferable_credits).forEach(function(key2) {
                                return (
                                    <td>{key2.institution}</td>
                                )
                            })}
                        </tr>
                    )})

                }
            </tbody>
            </table>
        </div>

     );
}
 
export default Home;

data[key].transferable_credits 是一个列表,因此您应该使用 map 而不是 Object.keys 循环。试试这个

import data from './data.json'

const Home = () => {

    return ( 
        <div className="home">
            <table>
                <thead>
                    <tr>
                        <th>Course Code</th>
                        <th>Vendor Institution</th>
                        <th>Vendor Course</th>
                    </tr>
                </thead>
            <tbody>
                {Object.keys(data).map(function(key, index) {
                    return (
                        <tr key={index}>
                            <td>{key}</td>
                            {data[key].transferable_credits.map(function(key2) {
                                return (
                                    <td>{key2.institution}</td>
                                )
                            })}
                        </tr>
                    )})

                }
            </tbody>
            </table>
        </div>

     );
}
 
export default Home;