2

I'm having an issue with trying to populate a multidimensional object in javascript before all of the dimensions are defined.

For example this is what I want to do:

var multiVar = {};
var levelone = 'one';
var leveltwo = 'two';

multiVar[levelone][leveltwo]['levelthree'] = 'test'

It would be extremely cumbersome to have to create each dimension with a line like this:

var multiVar = {};

multiVar['levelone'] = {};
multiVar['levelone']['leveltwo'] = {};
multiVar['levelone']['leveltwo']['levelthree'] = 'test'

The reason why I need to do it without iterative priming is because I don't know how many dimensions there will be nor what the keys it will have. It needs to be dynamic.

Is there a way to do that in a dynamic way?

4
  • Sorry - objects. Principle remains. Commented Oct 9, 2011 at 2:12
  • I don't understand what you're trying to do. What is this for? How will you fill it? Can you give an example of a filled in object? Commented Oct 9, 2011 at 2:16
  • I'm using it for JSON data being returned back from a server for Yahoo Fantasy Football league data... Commented Oct 9, 2011 at 2:25
  • What exactly are you trying to do with this JSON that you need this? Commented Oct 9, 2011 at 2:41

1 Answer 1

4

You could write a function which ensures the existence of the necessary "dimensions", but you won't be able to use dot or bracket notation to get this safety. Something like this:

function setPropertySafe(obj)
{
    function isObject(o)
    {
        if (o === null) return false;
        var type = typeof o;
        return type === 'object' || type === 'function';
    }

    if (!isObject(obj)) return;

    var prop;
    for (var i=1; i < arguments.length-1; i++)
    {
        prop = arguments[i];
        if (!isObject(obj[prop])) obj[prop] = {};
        if (i < arguments.length-2) obj = obj[prop];
    }

    obj[prop] = arguments[i];
}

Example usage:

var multiVar = {};
setPropertySafe(multiVar, 'levelone', 'leveltwo', 'levelthree', 'test');
/*
multiVar = {
    levelone: {
        leveltwo: {
            levelthree: "test"
        }
    }
}
*/
Sign up to request clarification or add additional context in comments.

2 Comments

Note that your isObject function will return true for isObject(null) and it will return false if you pass a function object, both cases could give you problems.
It works now. It could probably be done more elegantly using recursion but I'll leave that as an "exercise to the reader." ;-)

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.