1
var keys1 = ["foo", "moreFoo"],
value1 = "bar",
keys2 = ["foo", "ultraFoo"],
value2 = "bigBar";

I'd like to make a function which would build me an object :

object {
foo : {moreFoo: "bar", ultraFoo: "bigBar"}
}

I thought of taking each one of my arrays and doing the following :

function recursiveObjectBuild(object, keys, value) {
    var index = 0;
    function loop(object, index) {
        var key = keys[index];
        //Property exists, go into it
        if (key in object) {
            loop(object[key], ++index);
        //Property doesn't exist, create it and go into it
        } else if (index < keys.length-1) {
            object[key] = {};
            loop(object[key], ++index);
        //At last key, set value
        } else {
            object[key] = value;
            return object;
        }
    }
    return loop(object, 0);
}

Which should work IMO but doesn't (infinite loop, must be a stupid mistake but can't see it).

And I'm sure there must be a much simpler way

5
  • Please explain with pseudo-code, it would be better :) Commented Jun 24, 2013 at 16:19
  • Seems line#6 is an issue. i don't see where "object" gets set: " if (key in object) {". Also, why not use JSON in your object builder? Commented Jun 24, 2013 at 16:20
  • @mohamed-abshir object is received as a parameter by the recursive function How would you do it with JSON ? Commented Jun 24, 2013 at 16:49
  • @flav the array of keys is a nested set of keys. [foo, bar, foobar] means that i want to set the properties to Object.foo.bar.foobar Also, all those properties will be defined in the same object Commented Jun 24, 2013 at 16:50
  • Here is the Json syntax for the sample above: var JSONObject= { "foo":"bar", "moreFoo":"bigBar", "Altrafoo":bigBar }; Commented Jun 24, 2013 at 17:30

1 Answer 1

1

Try the following:

function objectBuild(object, keys, value) {
    for (var i = 0; i < keys.length-1; i++) {
        if (!object.hasOwnProperty(keys[i]))
            object[keys[i]] = {};
        object = object[keys[i]];
    }
    object[keys[keys.length-1]] = value;
}

Example usage (see it in action):

var object = {};
objectBuild(object, ["foo", "moreFoo"], "bar");
objectBuild(object, ["foo", "ultraFoo"], "bigBar");
// object --> {foo: {moreFoo: "bar", ultraFoo: "bigBar}}
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.