Suppose I have the following string: plan.details.notes
(Note: this string can have more/less sub nodes) and I have a value that should be set to it once it has been destructured, ie. "hello".
Here's what I want to achieve:
{
plan {
details {
notes: "hello"
}
}
}
I currently have the following code:
function recursiveSplitIntoObject(string, delimiter, value) {
if (!string) return {}
let stringToSplit = string
const returnObj = {}
while (stringToSplit.indexOf(delimiter) >= 0) {
const split = string.split(delimiter)
returnObj[split[0]] = { [split[1]]: value }
stringToSplit = split[1]
}
console.log(returnObj)
}
I'm not sure how to assign a dynamic object inside the [split[1]]: value
. I maybe close but I can't figure it out. Can anyone lead me to the right direction? Thanks!
CodePudding user response:
Remove the last key, process all other keys and finally assign the last key:
function recursiveSplitIntoObject(string, delimiter, value) {
let start = {},
curr = start,
keys = string.split(delimiter),
last = keys.pop()
for (let key of keys)
curr = (curr[key] = {})
curr[last] = value
return start
}
console.log(
recursiveSplitIntoObject('plan.details.notes', '.', 'hello'))
CodePudding user response:
In that case I would really consider using recursion, as it simplifies the way we can think of this problem.
The idea is to split the string into chunks using the delimeter, and when reaching to the last piece, assign the value, otherwise, call the recursive function with the tail of the array:
function rec(chunks, value) {
if (chunks.length === 1) {
return { [chunks[0]]: value };
}
return { [chunks[0]]: rec(chunks.slice(1), value) };
}
function recrusiveSetValue(str, value) {
const chunks = str.split('.');
return rec(chunks, value);
}
console.log(recrusiveSetValue('foo.bar.baz', 'hello'))