Add dictionary entry by variable

Hi, I want to populate a dict dynamically where the key is a multidimensional string in the dict, ex:

var dict = {}
var path = 'a.b.c'

dict[path] = 55

// this makes dict look like this
{'a.b.c': 55}

// expected result
{a: {b: {c: 55}}}

How can i get this?

What have you tried to get this effect so far?

I’m actually having trouble defining an easier approach to do this. Initially, my idea is making a function that goes through the entries of path.split(‘.’) and checks if the relative path exists in the dict. If not, I’ll create the entries and finally set the value. If this is the best way, I can do it. I just wanted to check if there’s an easier way.

Its easier to start with something that works and then refine it later

I end this way (it works), if anyone knows of a more performatic way I would appreciate it.

var __defaultDB = {};
document.querySelectorAll('[data-i18n]').forEach((el)=>{ // iterate over itens on doc
    let itemPath = el.dataset.i18n.split('.'); // array with entries
    let target = __defaultDB; // pointer for last item on path
    for(let i = 0; i < itemPath.length; i++){
        if(!target.hasOwnProperty(itemPath[i])){
            if(i == itemPath.length - 1){target[itemPath[i]] = el.innerHTML}
            else{target[itemPath[i]] = {}}
        }
        target = target[itemPath[i]];
    }
})

JavaScript doesn’t allow for access of an object that doesn’t already exist, you are not going to find an easier approach

1 Like