当结构基于数组时,如何将模型映射到表? [英] How to map model to table when the structure is array based?

查看:66
本文介绍了当结构基于数组时,如何将模型映射到表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下:

{
    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.

接近步骤:


  1. 制作键[ ] 来自每个列记录的 column.id

  2. 遍历行[]

  3. 每个循环,而 keys.length 创建一个对象 {keys [j]:row [k]}

  4. 推送到数组

  5. 重新创建原始 JSON 但是用对象替换数组

  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

我真的很难将其转换为代码,特别是在 rows [] 解析和创建对象。是的,我确信必须有一种有效的方法来实现这一目标。

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.

推荐答案

这是你能做的。使用Array.map和forEach。

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

这篇关于当结构基于数组时,如何将模型映射到表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆