簡體   English   中英

如何從嵌套的對象數組中獲取值 - React JS

[英]How to get values from nested array of objects - React JS

我正在嘗試從我的 data.json 中獲取由對象數組組成的值。 我正在嘗試通過對 json 數據使用 map 方法來獲取值。 我的 Json dat 結構類似於 Array->Object->Array-Object([{[{}]}])。 這就是數據在 Json 中的結構方式。 我已經寫下了 Json 數據和邏輯來獲取值。 每當我試圖從(對象的內部數組)中獲取值時,我都會得到未定義的結果。 任何人都可以幫助我如何解決這個問題。 提前致謝!

[
  {
    "key": "row-0",

    "cells": [
      {
        "key": "cell-0",
        "id": "ID-0",
        "headerName": "Name",
        "CustomerName": "ABC"
      },

      {
        "key": "cell-1",
        "id": "ID-1",
        "headerName": "RegID",
        "CustomerID": "P-01"
      },

      {
        "key": "cell-2",
        "id": "ID-2",
        "headerName": "Detail",
        "Deatil": "Abc"
      }
    ]
  },

  {
    "key": "row-1",

    "cells": [
      {
        "key": "cell-1",
        "id": "ID-1",
        "headerName": "Name",
        "CustomerName": "CDE"
      },

      {
        "key": "cell-2",
        "id": "ID-2",
        "headerName": "RegID",
        "CustomerID": "P-02"
      },

      {
        "key": "cell-3",
        "id": "ID-3",
        "headerName": "Detail",
        "Deatil": "CDE"
      }
    ]
  }
]

//邏輯

{mockData.map((values, index) => {
        console.log("VALUES", values);
        return values.cells.map(({ headerName, ...rest }) => {
          console.log("JSON", JSON.stringify(rest));
          console.log("REST", rest.CustomerName);---> getting undefined(I tried many approach everything is giving me undefined)
        });
      })}

我為你創建了一個例子

正如上面評論中提到的.. 沒有 customerName 的元素將給出未定義的。

 let mockData = [{ "key": "row-0", "cells": [{ "key": "cell-0", "id": "ID-0", "headerName": "Name", "CustomerName": "ABC" }, { "key": "cell-1", "id": "ID-1", "headerName": "RegID", "CustomerID": "P-01" }, { "key": "cell-2", "id": "ID-2", "headerName": "Detail", "Deatil": "Abc" } ] }, { "key": "row-1", "cells": [{ "key": "cell-1", "id": "ID-1", "headerName": "Name", "CustomerName": "CDE" }, { "key": "cell-2", "id": "ID-2", "headerName": "RegID", "CustomerID": "P-02" }, { "key": "cell-3", "id": "ID-3", "headerName": "Detail", "Deatil": "CDE" } ] } ]; mockData.map((values, index) => { console.log("VALUES", values); return values.cells.map(({ headerName, ...rest }) => { console.log("JSON",rest); console.log("Key:", rest.key); console.log("ID:", rest.id); console.log("CustomerName:", rest.CustomerName ? rest.CustomerName : 'NA' ); }); })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM