Skip to content

Commit

Permalink
Add a getObjectProperty util function.
Browse files Browse the repository at this point in the history
It knows how to do dotted property gets.

Part of #50.
  • Loading branch information
jkomoros committed Jul 22, 2023
1 parent 1203490 commit f0a7aaa
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,17 @@ const ILLEGAL_NAME_CHARS = /[^a-zA-Z0-9_-]/g;

export const safeName = (input : string) : string => {
return input.replace(ILLEGAL_NAME_CHARS, '_');
};

export const getObjectProperty = (obj : {[name : string]: unknown}, path : string) : unknown => {
if (!obj || typeof obj != 'object') throw new Error(`obj must be an object but had the value: ${obj}`);
const parts = path.split('.');
//if obj is an array then a get of a key like `1` will work as expected
//thanks to the weird way that javascript handles arrays.
const subObj = obj[parts[0]];
if (subObj === undefined) throw new Error(`obj had no property ${parts[0]}`);
if (parts.length > 1) {
return getObjectProperty(subObj as {[name : string] : unknown}, parts.slice(1).join('.'));
}
return subObj;
};

0 comments on commit f0a7aaa

Please sign in to comment.