Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting js array into dictionary map

I have this array:

["userconfig", "general", "name"]

and I would like it to look like this

data_structure["userconfig"]["general"]["name"]

I have tried this function:

inputID = "userconfig-general-name"

function GetDataByID(inputID){

    var position = '';

    for (var i = 0; i < inputID.length; i++) {
        var hirarchy = inputID[i].split('-');

        for (var index = 0; index < hirarchy.length; index++) {
            position += '["'+ hirarchy[index] +'"]';
        }
    }
    return data_structure[position];
}

while hirarchy is the array. I get the [position] as a string which is not working well.

how can I make a js function which builds the object path dynamically by an array?

like image 893
itay101 Avatar asked Dec 06 '25 03:12

itay101


1 Answers

var arr = ["userconfig", "general", "name"];
var dataStructure = arr.reduceRight(function (value, key) {
    var obj = {};
    obj[key] = value;
    return obj;
}, 'myVal');

Ends up as:

{ userconfig : { general : { name : 'myVal' } } }

Note that you may need a polyfill for the reduceRight method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

like image 157
deceze Avatar answered Dec 08 '25 16:12

deceze