[英]How to create dynamic table headers from JSON in React?
I have a JSON array of objects, I want to create a dynamic table columns/headers based on it in React. 我有一个对象的JSON数组,我想在React中基于它创建一个动态表列/标题。
The data: 数据:
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
]
I want to iterate through the array, get the key and add extra fields. 我想遍历数组,获取键并添加额外的字段。 So far I have:
到目前为止,我有:
columns() {
return Object.keys(Example[0]).map((key) => {
return {
cityName: key,
capital: false,
};
});
}
I get the keys, but they are unordered (random) and the extra field is added to all the objects. 我得到了键,但是它们是无序的(随机的),多余的字段被添加到所有对象中。 I want to get each key to use it as table header (column name) and be able to change
capital
for each object. 我想每一个键来使用它作为表头(列名),并能够改变
capital
为每个对象。 How can I do that in React? 我该如何在React中做到这一点?
You can use Array.map for this. 您可以为此使用Array.map。
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
];
example.map((obj) => {
return {
CITY : obj.city,
ID : obj.id
// Do whatever with the objects
}
})
arr => arr && arr[0] ? object.keys(arr[0]) : [];
确保数组中的所有项目都具有相同的键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.