Skip to content

Instantly share code, notes, and snippets.

@hamada-j
Last active June 9, 2021 18:40
Show Gist options
  • Save hamada-j/180acdf7aab7c714e95183d830837e23 to your computer and use it in GitHub Desktop.
Save hamada-j/180acdf7aab7c714e95183d830837e23 to your computer and use it in GitHub Desktop.
Creating nested object from keys
const
setValue = (object, path, value) => {
const
indices = { first: 0, second: 1 },
keys = path.replace(new RegExp(Object.keys(indices).join('|'), 'g'), k => indices[k]).split('.'),
last = keys.pop();
keys
.reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)
[last] = value;
return object;
},
data = { "dynamic.title": "Lorem Ipsum title", "dynamic.main_section.header.title": "Lorem Ipsum main section header title ", "dynamic.main_section.body.collection.first.title": "Lorem Ipsum main section body collection first title", "dynamic.main_section.body.collection.first.description": "Lorem Ipsum main section body collection first description", "dynamic.main_section.body.collection.first.id": "Lorem Ipsum main section body collection first id", "dynamic.main_section.body.collection.first.child.first.title": "Lorem Ipsum main section body collection first of first child title ", "dynamic.main_section.body.collection.first.child.first.id": "Lorem Ipsum main section body collection first of first child id ", "dynamic.main_section.body.collection.first.child.first.url": "https://loremipsum/1", "dynamic.main_section.body.collection.first.child.first.names.first": "John Doe", "dynamic.main_section.body.collection.first.child.first.names.second": "Jane Doe", "dynamic.main_section.body.collection.second.title": "Lorem Ipsum main section body collection second title", "dynamic.main_section.body.collection.second.description": "Lorem Ipsum main section body collection second description", "dynamic.main_section.body.collection.second.id": "Lorem Ipsum main section body collection second id", "dynamic.main_section.body.collection.second.child.first.title": "Lorem Ipsum main section body collection second of first child title ", "dynamic.main_section.body.collection.second.child.first.id": "Lorem Ipsum main section body collection second of first child id ", "dynamic.main_section.body.collection.second.child.first.url": "https://loremipsum/2", "dynamic.main_section.body.collection.second.child.second.title": "Lorem Ipsum main section body collection second of second child title ", "dynamic.main_section.body.collection.second.child.second.id": "Lorem Ipsum main section body collection second of second child id ", "dynamic.main_section.body.collection.second.child.second.url": "https://loremipsum/3" },
result = Object
.entries(data)
.reduce((r, [k, v]) => setValue(r, k, v), {});
console.log(result);
@hamada-j
Copy link
Author

hamada-j commented Jun 9, 2021

tested: pass🙃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment