javascript - 有没有更短的方法
问题描述
我编写了以下代码片段来生成一个对象。
{
"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
}
}
}
}
解决方案
如果您一次创建整个对象,您可能需要使用文字表示法:
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
}
推荐阅读
- python - 将字典字典转换为数据框
- latex - 如何在带有 - 的路径名中引用参考书目?
- css - 数据网格的css滚动阴影
- excel - 如何在 VBA 中将 Variant 转换为 Double 格式,反之亦然
- python - 如何将 QImage (Qt) 转换为 Mat (OpenCV) 并返回
- database - VisualStudios ASP.NET CORE 通过连接字符串链接到 AWS 数据库
- r - 在R中将字符串日期格式化为mdy时出错?
- android - 由于关键问题,我无法将我的 apk 上传到游戏商店。我总是使用相同的签名密钥
- python - 使用 Python Pandas,读取 xlsx 文件中写入的多个文件夹路径,并分别处理每个 csv 文件
- php - 我在使用 PHP 计算没有数据库的资产折旧时遇到了问题(主要是在哪里定义变量)