当结构基于数组时,如何将模型映射到表? [英] How to map model to table when the structure is array based?
本文介绍了当结构基于数组时,如何将模型映射到表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据如下:
{
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.
接近步骤:
- 制作
键[ ]
来自每个列记录的column.id
。 - 遍历
行[]
- 每个循环,而
keys.length
创建一个对象{keys [j]:row [k]}
- 推送到数组
- 重新创建原始
JSON
但是用对象替换
行
数组
- Make a
keys[]
fromcolumn.id
of each columns record. - Traverse the
rows[]
- Each loop, while
keys.length
create an object as{keys[j]:row[k]}
- Push to an array
- Recreate the original
JSON
but replaceRows
arrays withObjects
我真的很难将其转换为代码,特别是在 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屋!
查看全文