3

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?

4
  • Did you try anything? Commented Jul 22, 2014 at 7:13
  • what would be a value for such a structure? Commented Jul 22, 2014 at 7:17
  • I have edited my question, please review it again Commented Jul 22, 2014 at 7:18
  • Why you split inputID[i] by '-'? Commented Jul 22, 2014 at 7:21

3 Answers 3

2
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

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

1 Comment

Nice, +1. Note: arr.reverse().reduce( /*same callback*/, 'myVal' ) is equivalent
0

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

Comments

0

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;
}

Comments

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.