繁体   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