javascript - REACT.JS 填充自定义表头和表体

标签 javascript arrays reactjs

我正在尝试用对象数组填充表头和表体。我觉得这样真的很低效。有更好的方法吗?

clients:
            [
                {
                    Id: 0,
                    Name: "Camren Moore",
                    Country: "Wierdo Land",
                    City: "Oud-Turnhout",
                    Salary: "$36,738",
                    Actions: null,
                },
                {
                    Id: 1,
                    Name: "Adison Moore",
                    Country: "Crazy Land",
                    City: "Oud-Turnhout",
                    Salary: "$23,738",
                    Actions: null,
                }
            ]

let headers = [];
let body = [];
let i = 0;

for (var client of clients) {
  if (i === 0) {
    for (var key in client) {
      headers.push(key);
    }
  }
  i++;
  var ar = [];
  for (var value of headers)
    ar.push(client[value]);
  body.push(ar);
}

最佳答案

这是一个包含 2 个单行的解决方案

const clients =
[
                    {
                        Id: 0,
                        Name: "Camren Moore",
                        Country: "Wierdo Land",
                        City: "Oud-Turnhout",
                        Salary: "$36,738",
                        Actions: null,
                    },
                    {
                        Id: 1,
                        Name: "Adison Moore",
                        Country: "Crazy Land",
                        City: "Oud-Turnhout",
                        Salary: "$23,738",
                        Actions: null,
                    }
];
            

const header = Object.keys(clients[0]).map(key => key);
const body = clients.map(client => header.map(id => client[id]));

console.log(header)
console.log(body)
                            
           

我没有在 React 中实现它,因为我认为您的问题不是 React 特有的。

关于javascript - REACT.JS 填充自定义表头和表体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050391/

相关文章:

java - 创建数组的新实例时程序卡住

arrays - 从 rust 中从数组转换的字符串中删除多余的长度

reactjs - React应用程序抛出错误: Uncaught TypeError: Cannot read property 'shape' of undefined

reactjs - "[ts] Unterminated regular expression literal."

javascript - 使用新模型重置 Backbone 集合不会覆盖以前的模型吗?

javascript - 验证提供的值是否是 Lodash 的实例

javascript - AudioContext() 的多个来源

c - 在 C 中访问本地定义的结构

javascript - 在 SVG 文件中将文本作为 prop 传递 - React

javascript - 使用 AJAX 加载 VideoJS