How to map model to table when the structure is array based?

旧城冷巷雨未停 提交于 2020-01-11 13:04:17

问题


I have my data as following:

{
    meta: {
              format: "csv",
              info: "desc",
              columns: [
              {
                  id: "Name",
                  type: "Text",
                  length: 32          
              }, 
              {
                  id: "Text",
                  type: "Text",
                  length: 128
              }]
          },
    rows: [
              ["John","xxxx"],
              ["Alpha","yyyy"],
              ["Beta","wwww"],
              ["Gamma","zzzz"]]
}

Now, I am struggling to map the records to a Table control as Columns and Rows. Column seems straight forward, straight map, but the rows since lacks a mapping to column I wonder what could be the simplest way.

Approach Steps:

  1. Make a keys[] from column.id of each columns record.
  2. Traverse the rows[]
  3. Each loop, while keys.length create an object as {keys[j]:row[k]}
  4. Push to an array
  5. Recreate the original JSON but replace Rows arrays with Objects

I am really struggling to translate this into code specially at the rows[] parsing and creating Objects. Is there, I am sure there must be, an efficient way to achieve this.


回答1:


Here is what you could do. using Array.map and forEach.

var input = {
  meta: {
    format: "csv",
    info: "desc",
    columns: [{
      id: "Name",
      type: "Text",
      length: 32
    }, {
      id: "Text",
      type: "Text",
      length: 128
    }]
  },
  rows: [
    ["John", "xxxx"],
    ["Alpha", "yyyy"],
    ["Beta", "wwww"],
    ["Gamma", "zzzz"]
  ]
};


var columns = input.meta.columns.map((column) => {
  return column.id
});


var rows = input.rows.map((row) => {
  var obj = {};
  row.forEach((column, idx) => {
    obj[columns[idx]] = column;
  });
  return obj;
});

input.rows = rows;
console.log(input);


来源:https://stackoverflow.com/questions/40793535/how-to-map-model-to-table-when-the-structure-is-array-based

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!