What does I < mean in line 3 of your answer?
Comment on Can you help me with my JavaScript issue?
sleep_deprived@lemmy.world 9 months ago
The issue is that, in the function passed to reduce
, you’re adding each object directly to the accumulator rather than to its intended parent. These are the problem lines:
if (index == array.length - 1) { accumulator[val] = value; } else if (!accumulator.hasOwnProperty(val)) { accumulator[val] = {}; // update the accumulator object }
There’s no pretty way (that I can think of at least) to do what you want using methods like reduce
in vanilla JS, so I’d suggest using a for loop instead - especially if you’re new to programming. Something along these lines (not written to be actual code, just to give you an idea):
let curr = settings; const split = url.split("/"); for (let i = 0; i < split.length: i++) { const val = split[i]; if (i != split.length-1) { //add a check to see if curr[val] exists let next = {}; curr[val] = next; curr = next; } //add else branch }
It’s missing some things, but the important part is there - every time we move one level deeper in the URL, we update curr
so that we keep our place instead of always adding to the top level.
JackGreenEarth@lemm.ee 9 months ago
MyNameIsRichard@lemmy.ml 9 months ago
Lemmy’s code formatter has a bug where it escapes the less than symbol <
JackGreenEarth@lemm.ee 8 months ago
I fixed my code by using a recursive function as follows: