问题
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:
- 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
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