如何检查 javascript JSON 数组中是否已经存在值?
How to check if value already exists in javascript JSON array?
var ComfyJS = require("comfy.js");
var fs = require('fs');
const dataBuffer = fs.readFileSync('database.json');
const dataJSON = dataBuffer.toString();
const scoreBoard = JSON.parse(dataJSON);
ComfyJS.onChat = (user, message, flags, self, extra) => {
for (let i = 0; i < scoreBoard.length; i++) {
if (scoreBoard[i].name == user) {
console.log('The name already exist');
}
else{
scoreBoard.push({name:user,score:message});
}
}
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function (err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}
嗨,我是编码新手,我想构建一个 twitch 机器人,我想将我的数据保存在 JSON 文件中。 ComfyJS.onchat 当有人在聊天中输入内容时触发,我想将他们的姓名和消息(分数)作为值并将其保存在我的数据库中,但我需要将它们一一保存,所以如果名称已经存在于 JSON 文件我不想添加它。我该如何解决?
ComfyJS.onChat = (user, message, flags, self, extra) => {
const exists = scoreBoard.find(fn => fn.name === user)
if (exists) return;
scoreBoard.push({
name: user,
score: message
});
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function(err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}
var ComfyJS = require("comfy.js");
var fs = require('fs');
const dataBuffer = fs.readFileSync('database.json');
const dataJSON = dataBuffer.toString();
const scoreBoard = JSON.parse(dataJSON);
ComfyJS.onChat = (user, message, flags, self, extra) => {
for (let i = 0; i < scoreBoard.length; i++) {
if (scoreBoard[i].name == user) {
console.log('The name already exist');
}
else{
scoreBoard.push({name:user,score:message});
}
}
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function (err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}
嗨,我是编码新手,我想构建一个 twitch 机器人,我想将我的数据保存在 JSON 文件中。 ComfyJS.onchat 当有人在聊天中输入内容时触发,我想将他们的姓名和消息(分数)作为值并将其保存在我的数据库中,但我需要将它们一一保存,所以如果名称已经存在于 JSON 文件我不想添加它。我该如何解决?
ComfyJS.onChat = (user, message, flags, self, extra) => {
const exists = scoreBoard.find(fn => fn.name === user)
if (exists) return;
scoreBoard.push({
name: user,
score: message
});
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function(err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}