Kasper
Kasper

Reputation: 23

Check nested objects with an array of keys

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]] = {}

Upvotes: 2

Views: 1009

Answers (1)

Adrien
Adrien

Reputation: 9531

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).

Upvotes: 1

Related Questions