Skip to content

Commit

Permalink
Add a setObjectProperty utility function.
Browse files Browse the repository at this point in the history
Part of #50.
  • Loading branch information
jkomoros committed Jul 23, 2023
1 parent e151ec6 commit 0490c07
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,23 @@ export const getObjectProperty = (obj : {[name : string]: unknown}, path : strin
return getObjectProperty(subObj as {[name : string] : unknown}, parts.slice(1).join('.'));
}
return subObj;
};

export const setObjectProperty = (obj : {[name : string] : unknown}, path : string, value : unknown) : void => {
if (!obj || typeof obj != 'object') throw new Error(`obj must be an object but had the value: ${obj}`);
const parts = path.split('.');
if (parts.length == 1) {
obj[parts[0]] = value;
return;
}
if (obj[parts[0]] !== undefined) {
//The value exists, try to set in it.
//We can do the cast because the top of the method will check to verify it matches the shape
setObjectProperty(obj[parts[0]] as {[name : string] : unknown}, parts.slice(1).join('.'), value);
return;
}
//Sub object doesn't exist, we need to create it. Is it an array or object?
const subObject = isNaN(parseInt(parts[1])) ? {} : [];
obj[parts[0]] = subObject;
setObjectProperty(obj[parts[0]] as {[name : string]: unknown}, parts.slice(1).join('.'), value);
};

0 comments on commit 0490c07

Please sign in to comment.