简体   繁体   English

我如何获取 get api 调用的数据,格式为 reactjs 中 object 数组中的 object 嵌套数组?

[英]How can i fetch the data of an get api call which is in the format as nested array of object in array of object in reactjs?

  1. Firstly this is my api data data.首先这是我的 api 数据数据。
{
    "code": 200,
    "message": "Request fulfilled, document follows",
    "data": [
        {
            "sn": "ACC-LEW-1JY1-J4X2",
            "created_on": "2022-11-12T07:42:26.531786Z",
            "owner": "devtest01",
            "toy_user_type": 1,
            "shared_status": "Owned",
            "product_data": {
                "id": 179,
                "product_skuid": "any-name",
                "variant_id": "any-id",
                "product_name": "any-product-name",
                "product_type_val": "car-toy",
                "product_category_slug": "stunt-car",
                "desc": null,
            },
            "attribute_data": {
                "toy_distance_travelled": "0",
                "toy_time_played": "0",
                "toy_last_updated": "0",
                "toy_donuts": "0",
                "toy_rash_drives": "0",
                "toy_smooth_drives": "0",
                "toy_top_boost": "0",
                "toy_tank_size": "0",
                "toy_draft_collector": "0",
                "toy_acceleration": "0",
                "toy_braking": "0",
                "toy_name": "",
                "toy_last_played": "",
                "toy_experience": "0",
                "toy_drifts": "0",
                "toy_top_speed": "0",
                "drifts": "0",
                "toy_last_maintainence_distance": "0"
            },
            "game_attribute_data": [
                {
                    "attr_key": "td_distance_travelled",
                    "value": 21,
                    "sync_version": 3
                },
                {
                    "attr_key": "td_time_played",
                    "value": 8,
                    "sync_version": 3
                },
                {
                    "attr_key": "td_drifts_completed",
                    "value": 3,
                    "sync_version": 3
                }
            ]
        },
    ],
    "error": null,
    "server_time": "2022-11-21T12:57:44.319Z"
}
  1. I want to access the data of game_attribute_data.我想访问 game_attribute_data 的数据。 I tam trying to use map function but I am unable to get the data.我正在尝试使用 map function 但我无法获取数据。

  2. This is my api call using fetch method in React.js这是我在 React.js 中使用 fetch 方法调用 api

const allToysData = async () => {
    await fetch(
      `URL`,
      {
        method: "GET",
        headers: {
          Authorization: "token"
        },
        redirect: "follow"
      }
    )
      .then(response => response.json())
      .then(data => {
        const toysdata = data.data;
        const updatedToysData = toysdata.map(
          (x: {
            created_on: any;
            owner: any;
            shared_status: any;
            sn: any;
            attribute_data: any;
            product_data: any;
            game_attribute_data: any;
          }) => ({
            created_on: x.created_on,
            owner: x.owner,
            shared_status: x.shared_status,
            sn: x.sn,
            toy_drifts: x.attribute_data.toy_drifts,
            toy_time_played: x.attribute_data.toy_time_played,
            toy_last_played: x.attribute_data.toy_last_played,
            toy_last_maintainence_distance: x.attribute_data.toy_last_maintainence_distance,
            product_skuid: x.product_data.product_skuid,
            product_image_1x: x.product_data.data.product_image_1x,
            game_attribute_data: x.game_attribute_data.map(x => x),
          })
        );

        const result = updatedToysData.map(x => x.game_attribute_data);
        setToyAttribute(updatedToysData);
        setArrToys(updatedToysData);
      })
      // eslint-disable-next-line no-console
      .catch(error => console.log(`Error: ${error}`));
  };

  1. I want to show the data of game_attribute_data in a table.我想在表格中显示 game_attribute_data 的数据。 How should I access the data in React.js.我应该如何访问 React.js 中的数据。

I already tried to get the data using map function but the data is not rendering in table so Please show me where my mistake might be.我已经尝试使用 map function 获取数据,但数据未在表格中呈现,所以请告诉我我的错误可能在哪里。

{
    data.data
    .map((item)=>item.game_attribute_data)
    .map((game_attribute_data)=>(game_attribute_data)
    .map((value,key)=>{

    return <tr key={key}>
      <td>{value.attr_key}</td>
      <td>{value.value}</td>
      <td>{value.sync_version}</td>
    </tr>
  }))
}

Here's the snippet.这是片段。 View it on fullpage在整页上查看

 // Get a hook function const {useState} = React; const Example = ({title}) => { const [data,setData] = useState({ "code": 200, "message": "Request fulfilled, document follows", "data": [ { "sn": "ACC-LEW-1JY1-J4X2", "created_on": "2022-11-12T07:42:26.531786Z", "owner": "devtest01", "toy_user_type": 1, "shared_status": "Owned", "product_data": { "id": 179, "product_skuid": "any-name", "variant_id": "any-id", "product_name": "any-product-name", "product_type_val": "car-toy", "product_category_slug": "stunt-car", "desc": null, }, "attribute_data": { "toy_distance_travelled": "0", "toy_time_played": "0", "toy_last_updated": "0", "toy_donuts": "0", "toy_rash_drives": "0", "toy_smooth_drives": "0", "toy_top_boost": "0", "toy_tank_size": "0", "toy_draft_collector": "0", "toy_acceleration": "0", "toy_braking": "0", "toy_name": "", "toy_last_played": "", "toy_experience": "0", "toy_drifts": "0", "toy_top_speed": "0", "drifts": "0", "toy_last_maintainence_distance": "0" }, "game_attribute_data": [ { "attr_key": "td_distance_travelled", "value": 21, "sync_version": 3 }, { "attr_key": "td_time_played", "value": 8, "sync_version": 3 }, { "attr_key": "td_drifts_completed", "value": 3, "sync_version": 3 } ] }, ], "error": null, "server_time": "2022-11-21T12:57:44.319Z" }) return ( <table > <thead> <tr> <th>Attr Key</th> <th>Value</th> <th>Sync Version</th> </tr> </thead> <tbody> { data.data.map((item)=>item.game_attribute_data).map((game_attribute_data)=>(game_attribute_data).map((value,key)=>{ console.log(value) return <tr key={key}> <td>{value.attr_key}</td> <td>{value.value}</td> <td>{value.sync_version}</td> </tr> })) } </tbody> </table> ); }; // Render it ReactDOM.createRoot( document.getElementById("root") ).render( <Example title="Example using Hooks:" /> );
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

According to your latest comment above, you're only looking for help getting & storing game_attribute_data separate from the rest of the API response, correct?根据您上面的最新评论,您只是在寻求帮助获取和存储与 API 响应的game_attribute_data分开的 game_attribute_data,对吗? If so, here's what I'd recommend:如果是这样,这就是我的建议:

  1. Create a new state variable to store this data.创建一个新的 state 变量来存储此数据。 Ex:前任:
const [gameAttribData, setGameAttribData] = useState([]);
  1. In your allToysData function, instead of mapping through the API response data, I would probably create a few variables (one for each unique state variable you're going to end up setting), loop through the response data (using .forEach ), and update each variable for each element you look at.在你的allToysData function 中,我可能会创建一些变量(而不是通过 API 响应数据进行映射)(一个用于你将最终设置的每个唯一的 state 变量),循环响应数据(使用.forEach ),以及为您查看的每个元素更新每个变量。 Example for game_attribute_data : game_attribute_data示例:
.then(data => {
  const newGameAttribData = [];

  // Loop through API response data
  data.data.forEach((x: {
    created_on: any;
    owner: any;
    shared_status: any;
    sn: any;
    attribute_data: any;
    product_data: any;
    game_attribute_data: any;
  }) => {
    // Add this element's data to arrays
    newGameAttribData.push(x.game_attribute_data);
  });

  // Update your state variables
  setGameAttribData(newGameAttribData);
});

Now you should be able to access gameAttribData outside of this function so you can render it to the screen.现在您应该能够访问此gameAttribData之外的 gameAttribData,以便将其呈现到屏幕上。 Hopefully you can adapt the above code for your use (I'm not sure exactly how you're wanting to render it to the screen).希望您可以调整上面的代码以供您使用(我不确定您希望如何将其呈现到屏幕上)。

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

相关问题 如何从 state 的数据中获取 object 数组并计入 reactjs - How can i get array of object from this data for state and count in reactjs 如何 map 我从 api 调用 usestate 变量获得的 object 数组所需的数据 - How to map the required data of array of object which i got from api call to usestate variable 如何获取作为对象而非数组的 Firebase 数据(实时数据库)? - How can I fetch Firebase data (Realtime Database) that is an object, not an array? 如何从嵌套在数组中的 object 中获取 id 元素 - How can i get a id element from an object which is nested within an array 如何从对象数组中获取数据,并通过 API 端点将其传递到 .fetch() 使用 React 所需的对象值? - How can I fetch data from an array of objects, pass it through an API end point to .fetch() the needed object value using React? 如何访问嵌套在对象内的数组 - How can I get to an array nested inside an object 如何在 object 的嵌套数组中获取数据 - How to get data inside a Nested Array of object 如何捕获通过HTTP GET的api调用返回的Array对象? - How can I capture the Array object returned by an api call through HTTP GET? 如何将嵌套对象“解包”为数组? - How can I “unpack” a nested object as an array? 更新 ReactJs 数组中的嵌套 object - Update nested object in array in ReactJs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM