简体   繁体   English

显示 JavaScript 中嵌套的 object 个对象的值

[英]Show values from a nested object of objects in JavaScript

I have a nested object of objects, I need to show some data from it.我有一个嵌套的 object 对象,我需要显示其中的一些数据。 The object is: object 是:

{
"2": {
   "id": 2,
        "username": "mark",
        "position": "Director",
        "branch": "NY Branch",
        "name": "Mark Branson",
        "attendance": {
            "2022-11-01": {
                "times": [],
                "status": "holiday"
            },
            "2022-11-02": {
                "times": [
                    "11:05:31",
                    "11:51:30",
                    "12:59:50"
                ],
                "status": "late"
            },
            "2022-11-03": {
                "times": [
                    "10:24:17",
                    "11:05:20",
                    "11:10:09"                  
                ],
                "status": "late"
            },
},
"4": {
  "id": 4,
        "username": "john",
        "position": "Manager",
        "branch": "SF Branch",
        "name": "John Miller",
        "attendance": {
            "2022-11-01": {
                "times": [],
                "status": "holiday"
            },
            "2022-11-02": {
                "times": [
                    "11:05:31",
                    "11:51:30",
                    "12:59:50"
                ],
                "status": "present"
            },
            "2022-11-03": {
                "times": [
                    "10:24:17",
                    "11:05:20",
                    "11:10:09"                  
                ],
                "status": "late"
            },
},
"5": {
   "id": 5,
        "username": "emma",
        "position": "HR",
        "branch": "Head Branch",
        "name": "Emma Smith",
        "attendance": {
            "2022-11-01": {
                "times": [],
                "status": "holiday"
            },
            "2022-11-02": {
                "times": [
                    "11:05:31",
                    "11:51:30",
                    "12:59:50"
                ],
                "status": "late"
            },
            "2022-11-03": {
                "times": [
                    "10:24:17",
                    "11:05:20",
                    "11:10:09"                  
                ],
                "status": "present"
            },
},
}

The design I need to implement is this我需要实现的设计是这样的

Design设计

The React Code I have written so far is:到目前为止我写的 React 代码是:

import { useEffect, useState } from "react";
import axios from "axios";

export default function App() {
  const [object, setUsers] = useState([]);

  useEffect(() => {
    const instance = axios.create({
      baseURL: "https://test.com/",
      headers: {
        Authorization: "Bearer token",
      },
    });
    const getData = async () => {
      const userData = await instance.get("/test");
      setUsers(userData.data);
    };
    getData();
  }, []);
  console.log("Object", object);
  console.log("Object.keys(object)", Object.keys(object));

  console.log("Attendance", Object.entries(object));

  let nameData = [];

  Object.keys(object).forEach(function (key) {
    console.log("Name", object[key].name);
    nameData.push(object[key].name);
  });

  console.log("nameData", nameData);

  let newAttendanceData = [];

  Object.keys(object).forEach(function (key) {
    console.log("Attendence Data", object[key].attendance);
    console.log(
      "Attendence Data of 2 Nov",
      Object.keys(object[key].attendance)[1]
    );
    console.log(
      "Attendence Data of 2 Nov value",
      Object.keys(object[key].attendance)[1]
    );
    newAttendanceData.push(object[key].attendance);
  });

  console.log("newAttendanceData", newAttendanceData);

  return (
    <div className="App">
      <div>
        <table>
          <tr>
            <th> Date</th>
            <th> Name </th>
            <th> Status </th>
          </tr>
          <tr>
            <td>
              <div>{nameData && nameData.map((name) => <div>{name}</div>)}</div>
            </td>
          </tr>
        </table>
      </div>
    </div>
  );
}

This is not properly written to show the data according to the design, what would be the proper way to map these object data so that the data can be displayed as per the design?这不是按照设计正确地显示数据,map这些object数据的正确方法是什么,以便数据可以按照设计显示? Need a way to get data from the nested object structure.需要一种从嵌套的 object 结构中获取数据的方法。

Why nesting id: 2 in the parent 2 to complicate your work?为什么嵌套id: 2在 parent 2中使你的工作复杂化? You can simply save them like this您可以像这样简单地保存它们

{
 2: {
  "username": "mark",
  "position": "Director",
  "branch": "NY Branch",
  "name": "Mark Branson",
  ...
 },
}

or要么

{
 {
   "id": 2,
   "username": "mark",
   "position": "Director",
   "branch": "NY Branch",
   "name": "Mark Branson",
   ...
 },
}

Anyway I'll solve it with your data structure in a basic way.不管怎样,我会用你的数据结构以一种基本的方式解决它。 As the mockup, I see we only need the employee name, attendance date and status and we can get them like this作为模型,我看到我们只需要员工姓名、出勤日期和状态,我们可以这样得到它们

let newData = [];

Object.keys(object).forEach((key) => {
 const name = object[key].name;
 const attendances = object[key].attendance;
 for (let date in attendances) {
  newData.push({
   employeeName: name,
   date: date,
   status: attendances[date].status
  });
 }
});

You can push results into the newData in the way that you're comfortable to deal with, hope this help.您可以按照自己喜欢的方式将结果推送到newData中,希望对您有所帮助。

Here's one way to transform that data structure into one that's easier to work with for your needs.下面是一种将该数据结构转换为更易于满足您的需求的方法。 I corrected the typos in your input data structure.我更正了您输入数据结构中的拼写错误。 It wasn't clear whether the resulting data should be sorted, or in what order, so I included a quick demonstration sorted by date:不清楚结果数据是否应该排序,或者以什么顺序排序,所以我提供了一个按日期排序的快速演示:

 let transformData = inp => { let out = []; for (let person of Object.values(inp)) { for (let date of Object.keys(person.attendance)) { // capture a new record: out.push({ "name": person.name, "date": date, "status": person.attendance[date].status }) } } // sort here, if needed: out = out.sort((a, b) => { return a.date > b.date }); return out; } let data = { "2": { "id": 2, "username": "mark", "position": "Director", "branch": "NY Branch", "name": "Mark Branson", "attendance": { "2022-11-01": { "times": [], "status": "holiday" }, "2022-11-02": { "times": [ "11:05:31", "11:51:30", "12:59:50" ], "status": "late" }, "2022-11-03": { "times": [ "10:24:17", "11:05:20", "11:10:09" ], "status": "late" }, } }, "4": { "id": 4, "username": "john", "position": "Manager", "branch": "SF Branch", "name": "John Miller", "attendance": { "2022-11-01": { "times": [], "status": "holiday" }, "2022-11-02": { "times": [ "11:05:31", "11:51:30", "12:59:50" ], "status": "present" }, "2022-11-03": { "times": [ "10:24:17", "11:05:20", "11:10:09" ], "status": "late" }, } }, "5": { "id": 5, "username": "emma", "position": "HR", "branch": "Head Branch", "name": "Emma Smith", "attendance": { "2022-11-01": { "times": [], "status": "holiday" }, "2022-11-02": { "times": [ "11:05:31", "11:51:30", "12:59:50" ], "status": "late" }, "2022-11-03": { "times": [ "10:24:17", "11:05:20", "11:10:09" ], "status": "present" }, } } } console.log(transformData(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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