首页 > 解决方案 > 有没有更短的方法

问题描述

我编写了以下代码片段来生成一个对象。

{
    "2018": {
        "02": {
            "18": {
                "scheduledSlots": 0,
                "totalSlots": 0,
                "slots": null
            }
        }
    }
}

这感觉只是错误的方式

   const obj = {}
        obj[date[2]] = {};
        obj[date[2]][date[1]] = {};
        obj[date[2]][date[1]][date[0]] = {};
        const day = obj[date[2]][date[1]][date[0]];
        day.scheduledSlots = 0;
        day.totalSlots = 0;
        day.slots = null;

我只需要知道是否有更好的方法来解决这个问题

这是一个哈希映射。
它需要再增加一天。

{
    "2018": {
        "02": {
            "18": {
                "scheduledSlots": 0,
                "totalSlots": 0,
                "slots": null
            }
        }
        "03": {
            "12": {
                "scheduledSlots": 0,
                "totalSlots": 0,
                "slots": null
            }
        }
    }
}

标签: javascriptjson

解决方案


如果您一次创建整个对象,您可能需要使用文字表示法

const obj = {
    [date[2]]: {
        [date[1]]: {
            [date[0]]: {
                scheduledSlots: 0,
                totalSlots: 0,
                slots: null
            }
        }
    }
}

或者,如果您以后需要访问const day

const day = {
    scheduledSlots: 0,
    totalSlots: 0,
    slots: null
}
const obj = {
    [date[2]]: {
        [date[1]]: {
            [date[0]]: day
        }
    }
}

@EDIT如果您需要迭代,那么这应该可以完成工作:

Object.prototype._next = function(name)
{
    if(!this[name]) this[name] = {};
    return this[name];
}

const obj = {}
const day = obj._next(date[2])._next(date[1])._next(date[0]) = {
    scheduledSlots: 0,
    totalSlots: 0,
    slots: null
}

推荐阅读