gpt4 book ai didi

javascript - 如何使用 node.js 从 json 引用 key

转载 作者:搜寻专家 更新时间:2023-10-31 23:33:56 27 4
gpt4 key购买 nike

我将如何访问以下 json 数据

"users":{
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}

到目前为止我有这个,我知道这是完全错误的:

Object.keys(jsonevents["events"]).forEach(function(key) {
if(eventName == jsonevents["events"][key]["name"]){
if(jsonevents["events"][key]["users"]){
if(jsonevents['events'][key]["users"][message.author.id]){
delete jsonevents['events'][key]["users"][message.author.id];
fs.writeFile(eventsjson, JSON.stringify(jsonevents),'utf8');
sayMessage += "```User is no longer part of the event "+jsonevents['events'][key]["name"]+"```";
} else {
sayMessage += "```user is not in the event "+jsonevents['events'][key]["name"]+"```";
}
} else {
sayMessage += "```Why do we have no users```";
}
} else {
//sayMessage += "```No event found```";
}
});

我需要能够通过传入用户名来访问 key ,所以 user2 会给我 14300995184 这样我就可以使用它从事件。

最佳答案

您可以搜索Object.entries使用 find() 并返回正确的对象。它会返回一个 key/value 的数组,key 就是你想要的:

let users = {
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}

let found = Object.entries(users).find(([key, value]) => value.username === "user2")
console.log(found && found[0]) // found is undefined if not found

关于javascript - 如何使用 node.js 从 json 引用 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com