2

I've got an array (target) with keys to a series of nested objects. I need to make sure there is a object there before I set a value to it later on. This code is working but only so far as I can be bothered to repeat it.

How can I do this for n number of keys in the array without repeating this switch to infinity?

for t, index in target
    switch i
        when 1
            if object[target[0]] is undefined
                object[target[0]] = {}
        when 2
            if object[target[0]][target[1]] is undefined
                object[target[0]][target[1]] = {}
        when 3
            if object[target[0]][target[1]][target[2]] is undefined
                object[target[0]][target[1]][target[2]] = {}
        when 4
            if object[target[0]][target[1]][target[2]][target[3]] is undefined
                object[target[0]][target[1]][target[2]][target[3]] = {}
        when 5
            if object[target[0]][target[1]][target[2]][target[3]][target[4]] is undefined
                object[target[0]][target[1]][target[2]][target[3]][target[4]] = {}
        when 6
            if object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] is undefined
                object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] = {}
1
  • Look into tree iteration with recursion. Commented Mar 27, 2011 at 19:17

1 Answer 1

1

caveat untested code from the top of my head. But this should work...

current = object
for t in target
  current = (current[t] ?= {})

Or a more javascripty version:

target.reduce ((o,t)-> o[t]?={}), object

The first one is more legible, the second more elegant imho (and does not pollute the scope with current).

Sign up to request clarification or add additional context in comments.

1 Comment

Note that Array::reduce isn't available in all browsers. Here's an implementation you can use as a fallback: diveintojavascript.com/core-javascript-reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.