#32 后端数据处理


  • 0

    const parseData = (data) => data.rows.map(x => {
      return data.metaData.reduce((acc, meta, i) => ({ ...acc, [meta.name]: x[i] }) , {})
    })
    

  • 0

    es5写法
    const parseData = (data) => {
    var arr = []
    for(var i =0;i<data.rows.length;i++){
    var obj = {}
    for (var j =0;j<data.metaData.length;j++){
    obj[data.metaData[j].name] = data.rows[i][j]
    }
    arr.push(obj)
    }
    return arr
    }


  • 0

    const parseData = (data) => {
       var rows = data.rows, metaData = data.metaData, arr = [];
       for (let i = 0; i <= rows.length - 1; i++) {
           let obj = {};
           for (let j = 0; j <= rows[i].length - 1; j++) {
               obj[metaData[j].name] = rows[i][j];
           }
           arr.push(obj);
       }
    
       return arr;
    };

  • 0

    const parseData = (data) => {
    return data.rows.map(item => data.metaData.reduce((obj, col, index) => obj[col.name] = item[index], {}))
    }


  • 1

    const parseData = (data) => {
      const {rows, metaData} = data
      return rows.map(item => {
        let obj = {}
        metaData.forEach((meta, index) => {
          obj[meta.name] = item[index]
        })
        return obj
      })
    }

  • 0

    一行版的格式化版

    const parseData = ({rows, metaData}) => {
      return rows.map(row => {
        // reduce中转入2个参数,第一个是处理函数,第二个是默认值(空对象)
        return row.reduce((obj, value, index) => {
          // assign只要传入2个参数即可,一行版第一个空对象多余了,因为上面已给了默认值(空对象)
          return Object.assign(obj, {
            [metaData[index].name]: value
          })
        }, {}) // 这里,累加器的默认值是个空对象
      })
    }
    

  • 0

    const parseData = (data) => {
      const { rows, metaData } = data;
      if (!Array.isArray(rows) || !Array.isArray(metaData) || rows.length === 0 || metaData.length === 0) {
        return []
      }
      return rows.map(row => {
        return row.reduce((total, current, currentIndex) => {
          const key = metaData[currentIndex].name;
          total[key] = current;
          return total
        }, {})
      });
    };
    

  • 0

    const parseData = (data) => {

    const rows = data.rows;
    const metaList = data.metaData.map(meta=>{
    return meta.name;
    })

    const result = rows.map((row)=>{
    let info = {};
    for(var i in row){
    info[metaList[i]]=row[i];
    }
    return info;
    })

    return result;
    }
    萌新写法


  • 0

    @CodeHz
    const parseData = ({rows, metaData}) => rows.map(row => row.reduce((p, c, i) => Object.assign(p, {[metaData[i].name]: c}), {}))
    这样更好


  • 0

    const parseData = (data) => data.rows && data.rows.length && data.rows.map((v, i) => { let obj = {}; v.map((j, n) => obj[data.metaData[n].name] = v[n]); return obj; })


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待