itay101
itay101

Reputation: 53

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?

Upvotes: 3

Views: 9096

Answers (3)

Alessandro
Alessandro

Reputation: 1453

Recursive function

var array = ["userconfig", "general", "name"];

function toAssociative(array) {
    var index = array.shift();
    var next = null;
    if (array.length > 0) {
        next = toAssociative(array);
    }

    var result = new Array();
    result[index] = next;

    return result;
}

Upvotes: 0

deceze
deceze

Reputation: 522597

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

Upvotes: 2

Patrick Evans
Patrick Evans

Reputation: 42746

The below function will take an object to modify and an array filled with the properties needed:

function objPath(obj,path){
   path.forEach(function(item){
      obj[item] = {};
      obj = obj[item];
   });
}

var myobj = {};
objPath(myobj,["test","test2","test3"]);

console.log(myobj);
//outputs
Object {test: Object}
    test: Object
        test2: Object
            test3: Object

The function loops over the array creating the new object property as a new object. It then puts a reference to the new object into obj so that the next property on the new object can be made.

JSFiddle

Upvotes: 0

Related Questions