0

Здраствуйте, я хочу вывести данные из json в таблицу по датам. В json есть id (которое тоже хочу вывести) и данные. Вот вид json:

{
"1": [
    {
        "date_visit": "2021-06-20",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-21",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-22",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-23",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-24",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-25",
        "presences": true,
        "reason": "null"
    }
],
"4": [
    {
        "date_visit": "2021-06-19",
        "presences": true,
        "reason": "null"
    },
    {
        "date_visit": "2021-06-19",
        "presences": true,
        "reason": "null"
    }
]}

Я хочу всё это вывести в таблицу по датам, но не понимаю, как это сделать. Вот мой нынешний код:

import React, {useEffect, useState} from "react";
import {Table, TableBody, TableContainer, TableHead, Paper, Checkbox, Select, MenuItem} from '@material-ui/core';
import {StyledTableCell, StyledTableRow, tableStyles} from "./MainTableStyle";
import axios from "axios";
import {API_URL} from "../config";


const columns = [];
// eslint-disable-next-line array-callback-return
Array(/*new Date().getDate()*/ 24).fill(null).map((item, index) => index + 1).map((day, index) => {
    columns.push({id: index, label: day})
})

function MainTable() {
    const [data, setData] = useState([]);
    let result = "0";
    useEffect(() => {
        (async () => {
            const result = await axios.get(`${API_URL}/childrenGroupTable`, {
                headers: {Authorization: localStorage.getItem('token')}
            });

            setData(result.data);
        })();
    }, []);

    result = data.reduce((a, c) => (
        a[c.children_id] ?? (a[c.children_id] = []),
            a[c.children_id].push({
                date_visit: c.date_visit,
                presences: c.presences,
                reason: c.reason
            }),
            a
    ), {})

console.log(result)
    const classes = tableStyles();
    if (Object.keys(result).length === 0) {
        return (<h1 className={classes.table}>Загрузка</h1>)
    }
    return ();
 }

 export default MainTable;

1 ответ 1

0

Данные можно вывести примерно так: проходимся по ключам объекта и далее используя ключ рендерим массивы данных. У меня получилось примерно так:

// import React from "react";

const data = {
  1: [
    {
      date_visit: "2021-06-20",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-21",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-22",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-23",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-24",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-25",
      presences: true,
      reason: "null",
    },
  ],
  4: [
    {
      date_visit: "2021-06-19",
      presences: true,
      reason: "null",
    },
    {
      date_visit: "2021-06-19",
      presences: true,
      reason: "null",
    },
  ],
};

const App = () => {
  return (
    <div>
      {Object.keys(data).map((key) => {
        return (
          <div key={key}>
            <h3>Key is: {key}</h3>
            {data[key].map(({ date_visit, presences, reason }, idx) => (
              <div 
               key={idx}
               style={{
                 display: "flex",
                 justifyContent: "space-between",
                 width: "600px",
               }}
              >
                <div>date_visit: {date_visit}</div>
                <div>presences: {presences.toString()}</div>
                <div>reason: {reason}</div>
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
};

// export default App;

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.