How to map model to table when the structure is ar

2019-03-06 08:21发布

问题:

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