[英]ReactJS: Data Transformation with JSX
我正在尝试在React应用程序中使用JSX转换数据,但仍在努力弄清楚这样做的步骤。
输入:
const csvData =[
['title', 'A', 'B'] ,
['E01', 1 , 0] ,
['E02', 5 , 0] ,
['E03', 10, 2]
];
所需输出:
const jsonData =
{
"A":
{
"E01": 1,
"E02": 5,
"E03": 10
},
"B":
{
"E01": 0,
"E02": 0,
"E03": 2
}
}
我这样做的可怜尝试...
遍历嵌套数组中的每个数组(第一个包含标头的数组除外)
创建嵌套循环以遍历数组中的每个项目。
在此嵌套循环内,创建一个字典来存储标题,每个数组的第一项。 利用标题的索引提取数组中后续项的值。
export function transformData(data) { let dict = []; // array of header labels const arr = data[0]; // Looping through each row for (var i=1; i<data.length; i++) { // Create a dictionary by iterating through each header label, then extracting title and its value arr.map((f) => dict.push( {key: f, value: {key: data[i][0], value: data[i][f]} })) } console.log(dict); };
控制台打印结果:
0:
key:"title"
value:{key: "E01", value: undefined}
1:
key:"A"
value:{key: "E01", value: undefined}
2:
key:"B"
value:{key: "E01", value: undefined}
3:{key: "title", value: {…}} // header labels are repeated..
4:{key: "A", value: {…}}
5:{key: "B", value: {…}}
6:{key: "title", value: {…}}
7:{key: "A", value: {…}}
8:{key: "B", value: {…}}
您可以使用reduce
和内部forEach
方法并返回对象来执行此操作。
const csv = [ ['title', 'A', 'B'], ['E01', 1, 0], ['E02', 5, 0], ['E03', 10, 2] ]; const result = csv.reduce((r, a, i) => { if (i) { a.forEach((e, j) => { if (j) { let key = csv[0][j] if (!r[key]) r[key] = {} r[key][a[0]] = e; } }) } return r; }, {}) console.log(result)
您也可以先从带有slice
第一个数组中获取列,然后使用reduce来构建对象。
const csv = [ ['title', 'A', 'B'], ['E01', 1, 0], ['E02', 5, 0], ['E03', 10, 2] ]; const keys = csv[0].slice(1) const result = csv.slice(1).reduce((r, a) => { a.slice(1).forEach((e, i) => { let key = keys[i] if (!r[key]) r[key] = {} r[key][a[0]] = e }); return r; }, {}) console.log(result)
您可以使用嵌套的for循环来获得结果:
var arr = [ ['title', 'A', 'B'] , ['E01', 1 , 0] , ['E02', 5 , 0] , ['E03', 10, 2] ]; var obj = {}; for(var i = 1; i < arr[0].length; i++){ obj[arr[0][i]] = {}; for(var j = 1; j < arr.length; j++){ obj[arr[0][i]][arr[j][0]] = arr[j][i]; } } console.log(obj);
我认为这可能对您有用。 我已添加评论。 希望它对您有用!
const csvData =[
['title', 'A', 'B'] ,
['E01', 1 , 0] ,
['E02', 5 , 0] ,
['E03', 10, 2]
];
// Separates the header from the data
const header = csvData.shift();
// Takes out the first row as we are not going to use it.
header.shift();
// Create the output data
const output = {};
// Iterate each header value to create the keys. Ex { A: {}, B: {}}
for(let i=0; i<header.length; i++) {
const key = header[i];
// Creates the Key Property
output[key] = {};
// Assign the Values on the Key based on the rows with data
for (let j=0; j< csvData.length; j++) {
const row = [ ...csvData[j] ];
// As the first column is always the key property, we take it
const prop = row.shift();
// Then we take the value according the header index (i)
const value = row[i];
output[key][prop] = value;
}
}
console.log(output);
我也制造一个小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.