Home > Enterprise >  react js iterating through an object in jsx
react js iterating through an object in jsx

Time:10-01

This code in React.js need to show a simple table with cells filled by data from db.json, but the only thing I see is a blank page, I tried to console.log(cell) inside the td and the correct information was logged but yet nothing was shown on the screen.

Sheet.js

import React from 'react'

function Sheet() {
    const data = require('../store/db.json')
    const mySheet = data.sheet1

    return (
        <>
            <table>
                <tbody>
                    {
                        Object.entries(mySheet).forEach(([row, cols]) => (
                            <tr key={row}>
                                {
                                    Object.entries(cols).forEach(([col, cell]) => (
                                        <td key={`${row},${col}`}>
                                            {cell}
                                        </td>
                                    ))
                                }
                            </tr>
                        ))
                    }
                </tbody>
            </table>
        </>
    )
}

export default Sheet

db.json

{
    "sheet1": {
        "1": {
            "1": "1,1",
            "2": "1,2",
            "3": "1,3"
        },
        "2": {
            "1": "2,1",
            "2": "2,2",
            "3": "2,3"
        },
        "3": {
            "1": "3,1",
            "2": "3,2",
            "3": "3,3"
        }
    }
}

CodePudding user response:

The .forEach JS array method always returns undefined.

console.log([1, 2, 3].forEach(x => x * 2)) // -> undefined

If you want to return another array from a source array, use .map

console.log([1, 2, 3].map(x => x * 2)) // [2, 4, 6]
  • Related