Last active
April 16, 2024 13:19
-
-
Save biovisualize/3516e4bde982de1e57de3d126d5d89b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you have data like this | |
const dataExample = { | |
charts: [ | |
{ | |
id: "chart1", | |
something1: { | |
something2: 1 | |
}, | |
something3: { | |
histogram: [1, 2, 3] | |
} | |
} | |
] | |
} | |
// You want to map it to the schema that you defined for your chart | |
const mappingExample = { | |
id: "chart1", | |
label: "chart 1", | |
data: { | |
value: getChartValue("chart1"), | |
range: [0, 100], | |
histogram: getChartHistogram("chart1"), | |
} | |
} | |
// The trick is to have a flexible mapping function. If you do it without a library, it could look like this | |
function getChartValue(chartID) { | |
return dataExample | |
.charts.find(d => d.id === chartID) | |
.something1 | |
.something2 | |
} | |
// But if something1 is missing from one entry, the whole mapping will throw an error. | |
// So you can naively check for availability. | |
function getChartValue(chartID) { | |
const obj = dataExample.charts.find(d => d.id === chartID) | |
if (obj.something1 && obj.something1.something2) return obj.something1.something2 | |
else return null | |
} | |
// But it gets out of control pretty quickly. | |
// Loadash takes care of the availability checking (similar with Ramda, @irrelon/path, etc.). | |
_.get(dataExample, "charts").find({id: chartID}).get("something1", "something2") | |
// json-path traverses the json to find the key without knowing the path https://www.npmjs.com/package/json-find | |
JsonFind(dataExample).checkKey("something2") | |
// But here it will return the first match. So it would need a better syntax for matching | |
// JSON path is a flexible syntax for paths inspired by how xpath works for xml files https://goessner.net/articles/JsonPath/ | |
// Multiple libraries are using that syntax | |
jsonPath(dataExample, `$.charts[?(@.id ==="${chart1}")]..something2`) | |
// Notice how this one has matching and also `..` for recursive descent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment