Skip to content

Instantly share code, notes, and snippets.

@joeyred
Last active September 30, 2021 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeyred/402c5ecbb4bdf7f5a17b923efb487d7a to your computer and use it in GitHub Desktop.
Save joeyred/402c5ecbb4bdf7f5a17b923efb487d7a to your computer and use it in GitHub Desktop.
Uses a string representation of an object chain and traverses the actual object.
/**
* Takes a string representaion of an object chain and traverses the real object to the
* last key in the chain.
*
* @method _traverseObject
* @private
* @param {String} chain - String represenation of an object chain.
* @param {Object} object - The object to traverse.
* @return {*} - The new position in the object.
*/
function traverseObject(chain, object) {
const keys = chain.split('.');
let output = object;
for (let i = 0; i < keys.length; i++) {
output = output[keys[i]];
}
return output;
}
/**
* Takes a string representaion of an object chain and traverses the real object to the
* last key in the chain.
*
* @method _traverseObject
* @private
* @param {String} chain - String represenation of an object chain.
* @param {Object} object - The object to traverse.
* @return {*} - The new position in the object.
*/
function traverseObject<TObject, TOutput>(chain: string, object: TObject): TOutput {
const keys = chain.split('.')
// let output = object
let output = { ...object }
for (let i = 0; i < keys.length; i++) {
output = output[keys[i]]
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment