简体   繁体   中英

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 = {};
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?

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"
        }
    }
}
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM