Initializing a 'multidimensional' object in javascript

耗尽温柔 提交于 2019-12-11 06:17:31

问题


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?


回答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:

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


来源:https://stackoverflow.com/questions/7700991/initializing-a-multidimensional-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!