Created
October 4, 2022 19:49
-
-
Save hongphuc5497/7c85b7de45d6e4c6bee5230329766c61 to your computer and use it in GitHub Desktop.
Reduce dot-delimeter string to level object with reduce
This file contains hidden or 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
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