最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

创建一个javascript地图

运维笔记admin15浏览0评论

创建一个javascript地图

创建一个javascript地图

我开始学习JS,特别是Node.js,大约5-6个月前,我在Discord.js库中工作了很多,并且掌握了其他编程语言的知识。

我想使用Map()创建一种数据存储区,在我创建对象数组之前,Discord.js有一堆正在使用的地图,很高兴使用它们。

我的新目标是使用Electron创建一个小应用程序,我需要在地图中保存用户和程序列表,为了持久性我想将它们保存为JSON,如果可能的话,这里是我预先创建的JSON用户文件中的一些示例数据:

"user": [
    {
        "name": "David",
        "currentProgram": "program1",
        "currentPhase": "C",
        "workout": [
            {
                "name": "Workoutname",
                "load": "10", 
                "units": "kg"
            }
        ]
    },
    {
        "name": "Markus",
        "currentProgram": "program2",
        "currentPhase": "A",
        "workout": []
    }
]

程序文件:

"program": [
    {
        "name": "program1",
        "phases": [
            {
                "name": "A",
                "cycles": [
                    {
                        "name": "day 1",
                        "exercises": [
                            {
                                "name": "workout1",
                                "set": 4,
                                "repetitions": 8
                            },
                            {
                                "name": "workout2",
                                "set": 4,
                                "repetitions": 8
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

我的目标是做这样的事情:

var user = require('./user.json');

user.get("David").currentProgram = "program2";
user.get("David").currentPhase = "A";

var phase = program.get("program1").phases.get("A")

console.log(user.get("David"));

我没有使用JSON文件中显示的数组,而是创建了一个Map()

我正在寻找一些信息,如何创建一个地图最好的方式在我的情况下。如果有人有学习js的好方法,尤其是Map()我会很感激。我发现的唯一的东西是array.map或谷歌地图,但不同于Map()

另一个目标是将代码分成不同的文件,以便我有一个sperate文件,其中包含每个映射的构造。

非常感谢!

回答如下:

创建地图的小帮手:

 function toMap(array, prop){
   const map = new Map();
   for(const el of array) map.set(el[prop], el);
   return map;
}

可以像这样:

 const users = JSON.parse(require("fs").readFileSync('./user.json')).user;
 users.byId = toMap(users, "name");

 console.log( users.byId.get("jonas"));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论