Lately I had to read and set values in nested data structures of REST APIs very often. That was already slowly turning into work.
I can't remember how many times I wrote the following structures or similar in the last months.
const a = {}
if(typeof a ==='object') {
if(a['b'] !==undefined ) {
// do something
}
}
Alternatively you can also work with Optional chaining. However, this also has its challenges.
For this reason I wrote the auxiliary class Pathfinder. This is a small class that bundles all the queries.
The integration is done via import.
import {Pathfinder} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.23.0/dist/modules/data/pathfinder.js';
Methods
With this class come 4 methods exists
, deleteVia
, setVia
and getVia
. With these, structures can be manipulated quickly and easily.
getVia
First an example of how read access is possible.
new Pathfinder({
a: {
b: {
f: [
{
g: false,
}
],
}
}
}).getVia("a.b.f.0.g");
// ↦ false
setVia
To write a value you can use the setVia
method:
obj = {};
new Pathfinder(obj).setVia('a.b.0.c', true);
// ↦ {a:{b:[{c:true}]}}
Wildcards
A nice little additional feature is the use of wildcards. Here you can extract several values from a structure.
let value = new Pathfinder({
a: {
b: {
f: [
{
g: 1,
},
{
g: 2,
}
],
}
}
}).getVia("a.b.f.*.g");
console.log(value.forEach((a,b)=>{console.log(a,b)}));
// ↦ 1 "0"
// ↦ 2 "1"
The worst path you can choose is to choose none.
Voila that's it
Top comments (0)