We have an object, containing nested locations and their coordinates:
const data = {
name: 'World',
coords: '0,0',
sweden: {
name: 'Sweden',
coords: '61.7426757,8.4501191',
stockholm: {
name: 'Stockholm',
coords: '59.3261232,17.9120139',
sodermalm: {
name: 'Södermalm',
coords: '59.3142931,18.0266148',
},
},
},
};
given the data object, we read different locations coordinates by:
console.log({
world: data,
sweden: data.sweden,
stockholm: data.sweden.stockholm
});
but not all of the locations are defined in our data source, so when the data is queried, we need to fallback to the parent location if the location is not found:
console.log({
iran: data.iran, // should return world
taby: data.sweden.stockholm.taby, // should return stockholm
nasbyPark: data.sweden.stockholm.taby.nasbyPark, // should return stockholm since it's the closest available parent
});
Click to expand!
- We need to create a proxy to the source of the data.
const handler = {
get(target, prop) {
const value = target[prop] || target;
return value;
},
};
const proxy = new Proxy(data, handler);
now proxy.iran
is available, which is "deepEqual" to data
. First part of the problem is now solved.
2. Now we need to cover the cases where the value is nested. This requires to have new proxy when the returned value is an object as well.
const handler = {
get(target, prop) {
const value = target[prop] || target;
if (value && typeof value === 'object') {
return new Proxy(value, handler);
}
return value;
},
};
const proxy = new Proxy(data, handler);