Created
April 27, 2020 11:53
-
-
Save mark-buhagiar/0843fdc711f8aa46926117865c1512ee to your computer and use it in GitHub Desktop.
Expand path in object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ExpandFieldException extends Error {} | |
function expandPath(item: any, path: string): string { | |
var selectionRegex = /(^|\?|\.)(.+?)(?=(\?|\.|$))/g | |
var filterRegex = /(.+)=\((.+)\)/ | |
const getItemProperty = (item: any, propertyName: string) => { | |
if (!item || !Object.keys(item).includes(propertyName)) | |
throw new ExpandFieldException(path) | |
return item[propertyName] | |
} | |
var selections = path.match(selectionRegex) | |
let currentSelector = item | |
selections?.forEach((selection) => { | |
switch (selection.charAt(0)) { | |
case '.': | |
currentSelector = getItemProperty( | |
currentSelector, | |
selection.substring(1) | |
) | |
break | |
case '?': | |
selection = selection.substring(1) | |
var filter = selection.match(filterRegex) | |
if (filter === null) throw new ExpandFieldException(path) | |
const [, filterOn, filterFor] = filter | |
currentSelector = (currentSelector as any[]).find( | |
(property) => property[filterOn] === filterFor | |
) | |
break | |
default: | |
// This should only trigger for the first element at the start of string | |
currentSelector = getItemProperty(currentSelector, selection) | |
break | |
} | |
}) | |
return !!currentSelector ? currentSelector.toString() : '' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment