我编写了以下代码片段来生成一个对象。
{
"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;
我只是想知道是否有更好的方法来解决这个问题
这是一个 HashMap 。
它需要再增加一天。
{
"2018": {
"02": {
"18": {
"scheduledSlots": 0,
"totalSlots": 0,
"slots": null
}
}
"03": {
"12": {
"scheduledSlots": 0,
"totalSlots": 0,
"slots": null
}
}
}
}
最佳答案
如果您一次创建整个对象,您可能需要使用 literal notation :
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
}
关于javascript - 有没有更短的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50523594/