【问题标题】:ReactJS: Data Transformation with JSXReactJS:使用 JSX 进行数据转换
【发布时间】:2018-07-09 18:09:04
【问题描述】:

我正在尝试在 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
      }

}

我尝试这样做很糟糕......

  1. 遍历嵌套数组中的每个数组(第一个除外 包含标题的数组)

  2. 创建嵌套循环以遍历数组中的每个项目。

  3. 在这个嵌套循环中,创建一个字典来存储标题,每个数组中的第一项。利用标头的索引来提取数组中后续项的值。

    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() 而不是map(),因为您想从输入数组创建单个对象,而不是对象数组。

标签: javascript reactjs jsx


【解决方案1】:

您可以使用嵌套的 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);

【讨论】:

    【解决方案2】:

    您可以使用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)

    【讨论】:

      【解决方案3】:

      我认为这可能对你有用。我已经添加了 cmets。希望对你有用!

      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);
      

      我还创建了一个fiddle

      【讨论】:

        猜你喜欢
        • 2013-10-16
        • 2019-06-29
        • 2022-01-22
        • 2019-05-12
        • 1970-01-01
        相关资源
        最近更新 更多