[英]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.