How to implement a table in JSON
Optimal script to access a value in a table from row and column keys.
Example with the following table, which records the rankings of F1 world championship for teams.
2013 | 2014 | 2015 | |
Ferrari | 3 | 4 | 2 |
Mercedes | 2 | 1 | 1 |
Williams | 9 | 3 | 3 |
How to represent this table in a JSON file so that we can reach a result by giving the team name and year, thus achieving a sort of SQL query?
The most resources economical way is to establish a schema describing the headers of rows and columns, and then to declare a matrix corresponding to the complementary part of the table:
3 | 4 | 2 |
2 | 1 | 1 |
9 | 3 | 3 |
Schema:
var teams = [ "Ferrari" , "Mercedes", "Williams"]
var years = [ "2013", "2014", "2015"]
Matrix:
var results = [
[ 3, 4, 2],
[ 2, 1, 1],
[ 9, 3, 3]
]
Then a query is defined:
function request(team, year) {
var t = teams.indexOf(team)
var y = years.indexOf(year)
return results[t][y];
}
var team = "Williams"
var year = "2014"
var rank = request(team, year)
document.write(team + " ranking in " + year+ " : " + rank)
Demonstration:
Changing a value makes use of the same principle with an assignment instead: results [x] [y] = value.
Adding a row or column is done simply with the push or splice method of Array.
It is also possible for large tables to optimize the access by building an index:
var iteams = {}
for(var i in teams) {
iteams[teams[i]] = i
}
var iyears = {}
for(var i in years) {
iyears[years[i]] = i
}
Then we make a query directly like that:
var r = results[iteams[team], iyears[year]]