Reputation: 7765
I'm just kind of lousy with recursive functions.
I want to turn this...
const input = { regions: ["US", "CA", "LA"], checked: true };
...into the following, using recursion and reduce
:
const output = {
US: {
CA: {
LA: true
}
}
};
Help? I've tried lots of things, but my experiments are too embarrassing to share.
Upvotes: 0
Views: 137
Reputation: 50759
You don't need recursion here (and I would favour .reduceRight
), but, here is a different approach which uses a recursive function in case you're interested in how it could be done. You can destructure the first element from your array and use it as the key, then, set the value to the next call which would produce an object. If no key can be retrieved, you can return the value of checked
:
const input = { regions: ["US", "CA", "LA"], checked: true };
const getNested = ([key, ...r], end) => key ? {[key]: getNested(r, end)} : end;
console.log(getNested(input.regions, input.checked));
Upvotes: 2
Reputation: 370789
Iterate over the regions with reduceRight
, creating the nested object with an initial value of the checked
property, and surrounding it with the new object (the new accumulator) on every iteration:
const input = { regions: ["US", "CA", "LA"], checked: true };
const { regions, checked } = input;
const output = regions.reduceRight((a, prop) => ({ [prop]: a }), checked);
console.log(output);
Upvotes: 3