Skip to content Skip to sidebar Skip to footer

Initializing A 'multidimensional' Object In Javascript

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 =

Solution 1:

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:

functionsetPropertySafe(obj)
{
    functionisObject(o)
    {
        if (o === null) returnfalse;
        vartype = typeof o;
        returntype === '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"
        }
    }
}
*/

Post a Comment for "Initializing A 'multidimensional' Object In Javascript"