0

Assume I have an unknown string array such as:

arr = [fruit/bananas:10, fruit/apples/0:5, fruit/apples/1:8, fruit/apples/2:7, car/honda/civic:1];  

and I want to populate an object such that each array value is a path to its object value (ie arr becomes obj below):

obj = {
      'fruits' :{
               'bananas' : 10,
               'apples'  : [5,8,7]
       },
       'car'   :{
               'honda':{
                       'civic': 1
                }
       }
}; 

I am just wondering what type of recursive function would be best since the actual array length for each value is unknown so just splitting '/' and populating wouldn't work (that I could figure out)

1
  • Every recursion can be written as a loop (and in this case, even a quite trivial one). What have you tried? Please show us your attempt (edit the code into the post). Commented Sep 10, 2014 at 18:25

1 Answer 1

0

Try this:

var arr = ['fruit/bananas:10', 'fruit/apples/0:5', 'fruit/apples/1:8', 'fruit/apples/2:7', 'car/honda/civic:1'];

function createObject(array) {
    var out = {};
    array.forEach(function(value) {
        var current = out,
            last = current,
            data = value.split(':'),
            keys = data[0].split('/'),
            lastKey = keys.pop();

        keys.forEach(function(key) {
            if(!current[key]) {
                current[key] = {};
            }
            last = current;
            current = current[key];
        });
        if(lastKey === '0') {
            current = last[keys.pop()] = [];
        }
        current[lastKey] = +data[1];
    });
    return out;
}

console.log(createObject(arr));

Here is the jsfiddle-demo

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

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.