Skip to content

Instantly share code, notes, and snippets.

@hongphuc5497
Created October 4, 2022 19:49
Show Gist options
  • Save hongphuc5497/7c85b7de45d6e4c6bee5230329766c61 to your computer and use it in GitHub Desktop.
Save hongphuc5497/7c85b7de45d6e4c6bee5230329766c61 to your computer and use it in GitHub Desktop.
Reduce dot-delimeter string to level object with reduce
const db = EXAMPLE_DB;
const expand = "group.permissions.entities.nestedEntities.slug(searchValue)"
const buildAssocOptions = (str) => {
return str
.split('.')
.reverse()
.reduce((acc, val, index, arr) => {
let currentObj = {
model:
db[
val
.split('_')
.map((item) => item[0].toUpperCase() + item.substring(1))
.join('')
],
as: val,
include: {
...acc,
},
};
if (val == arr.at(1)) {
delete currentObj.include;
currentObj = {
...currentObj,
where: {
[arr.at(0).match(/.*?\(/)[0].slice(0, -1)]: arr.at(0).match(/\((.*?)\)/)[1],
},
};
}
return currentObj;
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment