簡體   English   中英

map 對象數組在不使用鍵名的情況下做出反應

[英]map array of objects to table in react without using name of the key names

我有一個數組,我想在不使用鍵的情況下渲染這個數組,因為鍵每次都不相同。 甚至下一個數組中的鍵數也不相同。 我嘗試使用 map function 但無法使用鍵名取得成功。


const array1 = [{"BRANCH":"84","NUM":"1356","COST":"25","METHOD":"15"},
{"BRANCH":"3","NUM":"2134", "COST":"425","METHOD":"5"},
{"BRANCH":"4","NUM":"1905","COST":"325","METHOD":"1"},
{"BRANCH":"56","NUM":"2350","COST":"14", "METHOD":"9"}] 

const array2 = [{"UNIT":"84", "COST":"25"},
{"UNIT":"3","COST":"425"},
{"UNIT":"4","COST":"325"},
{"UNIT":"56","COST":"14"}]

請建議我 map function 迭代此數組以呈現到表中。 謝謝

你可以這樣做:

注意:這只是一個示例代碼,請嘗試創建自己的邏輯以獲得更好的結果:

const array1 = [
  { BRANCH: "84", NUM: "1356", COST: "25", METHOD: "15" },
  { BRANCH: "3", NUM: "2134", COST: "425", METHOD: "5" },
  { BRANCH: "4", NUM: "1905", COST: "325", METHOD: "1" },
  { BRANCH: "56", NUM: "2350", COST: "14", METHOD: "9" }
];

const array2 = [{"UNIT":"84", "COST":"25"},
{"UNIT":"3","COST":"425"},
{"UNIT":"4","COST":"325"},
{"UNIT":"56","COST":"14"}]

const Table = ({item}) => {
    const items = Object.entries(item);
    return (
      <td>
        {
          items.map(([key,value]) => {
           return (
              <tr key={value}>{value}</tr>
             )
          })
        }
       </td>
    )
}

const createTable = ({arr}) => {
  return (
    arr.map(item => {
      return <Table {...item} />
    })
  )
};


<CreateTable arr={array1} />
<CreateTable arr={array2} />

我不太確定你想要什么。 我猜你想在使用 map 方法時使用索引作為鍵?

 const arr = [{"BRANCH":"3","NUM":"2134", "COST":"425","METHOD":"5"}, {"BRANCH":"4","NUM":"1905","COST":"325","METHOD":"1"}, {"BRANCH":"56","NUM":"2350","COST":"14", "METHOD":"9"}] const arrMap = arr.map((el,index) => { return [{key:index, ...el}] }) console.log(arrMap) // [ // [ { key: 0, BRANCH: '3', NUM: '2134', COST: '425', METHOD: '5' } ], // [ { key: 1, BRANCH: '4', NUM: '1905', COST: '325', METHOD: '1' } ], // [ { key: 2, BRANCH: '56', NUM: '2350', COST: '14', METHOD: '9' } ] // ]

像這樣的東西?

  const array1 = [
    { BRANCH: "3", NUM: "2134", COST: "425", METHOD: "5" },
    { BRANCH: "4", NUM: "1905", COST: "325", METHOD: "1" },
    { BRANCH: "56", NUM: "2350", COST: "14", METHOD: "9" }
  ];

  const array2 = [
    { UNIT: "84", COST: "25" },
    { UNIT: "3", COST: "425" },
    { UNIT: "4", COST: "325" },
    { UNIT: "56", COST: "14" }
  ];

  const tempFunc = (arrayItem) => {
    const obj = Object.keys(arrayItem);
    for (let i = 0; i < obj.length; i++) {
      const name = obj[i];
      const value = arrayItem[name];

      console.log("name:", name, " value:", value);
    }
  };

  array1.map((item) => tempFunc(item));
  array2.map((item) => tempFunc(item));

暫無
暫無

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

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