Convert Json Data To Table
Solution 1:
The answer https://stackoverflow.com/a/52199138/10320683 is of course correct, but if you need or want to stick to your specific code, you can put this below your json.map
(which should by the way use forEach and not map, since you do not use the returned array anyways)
for (var col in cols) {
for (row intable) {
if (!table[row].hasOwnProperty(col)) {
table[row][col] = "-";
}
}
}
The reason why your code did not work is that by iterating over the rows, you do not get all the possible type properties, which becomes clear if you inspect your table
variable: { a: {1: "1", 2: "0", 5: "1"}, b: {...}}
(this is missing the 3 type property), so by calling Object.values(table[row])
later on, you get the following array for your cells: ["1", "0", "1"]
, but you do have 4 columns, so the "Type 5" result (1) gets shifted one column to the left.
Also, you need to be careful because your code is relying on the sorting that Object.values() produces, which means that if you want to change the order of your columns, your code would not work.
Post a Comment for "Convert Json Data To Table"