通过嵌套数组中的 ID 显示数据库中的数据

Display data from database via ID from nested array

我正在尝试获取数据(余额和员工姓名)以显示给用户。我有一个 nested array,其中包含多个保存基本员工信息的对象。我需要访问的 id 在嵌套对象中 - 请参见下面来自 Mongo DB.

的数据结构示例

我面临的问题,我唯一可以访问的ID是第一个ID,我做了一些研究,mongo只显示最高ID。如何访问嵌套 ID 以显示我需要的数据?有可能吗?我已尝试按照代码所示映射到 Axios 请求中,但没有任何效果。

{
    "message": "Post found",
    "data": {
        "company": "HIJ",
        "_id": "60fb75123ca85f76447d2b58",
        "details": [
            {
                "employee": "aa",
                "date": "aa",
                "tax": "aa",
                "balance": "3",
                "fee": 11,
                "notes": "aa",
                "_id": "60fb75123ca85f76447d2b59"
            },
            {
                "employee": "bb",
                "date": "bb",
                "tax": "bb",
                "balance": "3",
                "fee": 12,
                "notes": "bb",
                "_id": "60fb75123ca85f76447d2b5a"
            }
        ],
        "__v": 0
    }
}
    

代码如下:

import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";

const Success = () => {
  const [company, setCompany] = useState("")
  const [balance, setBalance] = useState("");
  const [employee, setEmployee] = useState("");
  const { id } = useParams();

  useEffect(() => {
    axios
      .get(`http://localhost:5000/get-snapshot-id-test/${id}`)
      .then((res) => {
        console.log("res", res.data.data);
        setBalance(res.data.data.map((b) => b.details.map((innerary) => innerary.balance)));
        setEmployee(res.data.data.map((e) => e.details.map((innerary) => innerary.employee)));
      })
      .catch((err) => {
        console.log(err);
      });
  }, [setBalance, setEmployee, id]);


  return (    
     { balance === "0.00" && <h4>{employee} is paid in full.</h4> }
     { balance !== "0.00" && <h4>{employee} new balance: ${balance}.</h4>}
  );
};
export default Success;

答案是修复 Axios 请求中的地图。 Drew Reese 指出了 res.data.data.details 的正确方向。然后我需要获取该结果并指向所需的状态

 useEffect(() => {
axios
  .get(`http://localhost:5000/get-snapshot-id-test/${id}`)
  .then((res) => {
    console.log("RESPONCE", res.data.data.details);
    setBalance(res.data.data.details.map((r) => r.balance));
    setEmployee(res.data.data.details.map((r) => r.employee));
  })
  .catch((err) => {
    console.log(err);
  });
  }, [setBalance, setEmployee, setNotes, id]);