【问题标题】:delete user from json table in js从js中的json表中删除用户
【发布时间】:2019-01-24 17:42:08
【问题描述】:

所以我是 js 的初学者,我在 json 文件中有一个用户表,我正在制作一个帐户删除功能。我有一个查找设置来查找用户,它工作正常,但我不知道如何让它从文件中删除用户,任何帮助将不胜感激!

json:

{
    "users": [
        {
            "name": "ImBattleDash",
            "Id": "780748c5d4504446bbba3114ce48f6e9",
            "discordId": "471621420162744342",
            "dateAdded": 1548295371
        }
    ]
}

JS:

    function findJson() {
    fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
        if (err) message.channel.send('Invalid Code.')

        var arrayOfObjects = JSON.parse(data)
        let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)

        let linkEmbed = new Discord.RichEmbed()
        .setTitle('Account unlinked!')
        .setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
        .setColor('#a900ff');

        message.channel.send({embed: linkEmbed});

    })
}

编辑:不确定是数组还是表我对json不太了解

【问题讨论】:

  • 你可以使用filter。它使用逆逻辑/谓词作为find,并会导致一个不包含指定用户的数组。如何持久保存对文件的更改是一个不同的问题/问题。

标签: javascript arrays node.js json


【解决方案1】:

你需要使用:

  • Array#find 按给定条件查找给定用户。
  • Array#indexOf 获取在users 中找到的用户的索引
  • Array#spliceArray#indexOf 给出的索引开始删除一个元素:

const input = {
    "users": [
        {
            "name": "ImBattleDash",
            "Id": "780748c5d4504446bbba3114ce48f6e9",
            "discordId": "471621420162744342",
            "dateAdded": 1548295371
        }
    ]
}

const removeUser = (criteria, users) =>
   users.splice (users.indexOf (users.find (criteria)), 1)
   
   
removeUser (
   ({ Id, discordId }) =>
       Id == '780748c5d4504446bbba3114ce48f6e9' 
       && discordId == '471621420162744342',
     input.users
)

// Output: 0 <-- User has been removed!
console.log(input.users.length)

关于持久化更改,只需调用JSON.stringify (input),然后将内容写入所需的输出文件即可。查看其他问答:Writing files in Node.js

【讨论】:

  • 对于 const 输入,由于数组在 json 文件中而不是在 js 文件中,我应该放什么?对不起
  • @BattleDash 但是,您想从 JSON 文件中物理删除用户吗?我的意思是,你想写整个文件?
  • 是的,我基本上有两个文件,users.json 和 linkedusers.json,users.json 用于未经验证的用户(未链接),linkedusers.json 的用户 ID 与他们的 Discord ID 相关联。我正在制作 unlink 命令,该命令将从linkedusers.json中完全删除它们
  • @BattleDash 删除用户后,您只需在 Node 中使用 fs.writeFile 保存文件。
  • 是的,在链接命令中我使用fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4)
【解决方案2】:

在 Cat 和 Matias 的大力帮助下,我想出了这个有效的代码!

    function findJson() {
    fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
        if (err) message.channel.send('Invalid Code.')

        var arrayOfObjects = JSON.parse(data)
        let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)

        const input = arrayOfObjects;

        const removeUser = (criteria, users) =>
        users.splice (users.indexOf (users.find (criteria)), 1)

        removeUser (
        ({ Id, discordId }) =>
            Id == findEntry.Id 
            && discordId == findEntry.discordId,
            input.users
        )

        console.log('unlinked')

        fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
            if (err) throw err
            console.log('Done!')
        })


        let linkEmbed = new Discord.RichEmbed()
        .setTitle('Account unlinked!')
        .setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
        .setColor('#a900ff');

        message.channel.send({embed: linkEmbed});

    })
}

【讨论】:

    【解决方案3】:

    这里有一个快速教程给你: “用户”可以是数组(使用[])或javascript 对象(使用{}),由您选择。除非您使用数据库而不是 JSON 文件,否则不会有任何实际的表(尽管如果您的 JSON 表达式像您的示例一样简单,您几乎可以将其视为一个表。)——实际上,第三种选择将是使用javascript Map 类型,它就像一个增强的对象,但我不会在这里解决。

    虽然使用数组可以更轻松地为 所有 用户检索数据列表(因为数组更易于迭代),但使用对象可以更轻松地检索数据对于 single 用户(因为您可以通过其键直接指定您想要的用户,而不是需要遍历整个数组直到找到您想要的用户。)我将向您展示一个示例使用一个对象。

    示例代码中的单个用户是 javascript 对象的示例。 JSON 允许您将对象转换为字符串(用于存储、I/O 和人类可读性)并返回对象(以便 javascript 可以理解它)。您分别使用 JSON.stringify() 和 JSON.parse() 方法进行这些转换。该字符串必须是 JSON 格式,否则这将不起作用,您的示例 几乎 为 JSON 格式。

    为了符合 JSON 格式,您可以按如下方式构建用户对象。 (当然,我们正在查看字符串化版本,因为普通人无法轻松读取“实际”javascript 对象):

    "Users": {  // Each individual user is a property of your users object
      "780748c5d4504446bbba3114ce48f6e9":  // The Id is the key in the "key/value pair"
        { // The individual user object itself is the value in the key/value pair
        // Id is duplicated inside user for convenience (not necessarily the best way to do it)
          "id": "780748c5d4504446bbba3114ce48f6e9",
          "name": "ImBattleDash", // Each property of the user is also a key/value pair
          "discordId": "471621420162744342", //Commas separate the properties of an object
          "dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
        }, // Commas separate the properties (ie the individual users) of the users object
      "446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
      {                                   // This object is the second user's value 
        "id": "446bbba3114ce48f6e9780748c5d4504",
        "name": "Wigwam",
        "discordId": "162744342471621420",
        "dateAdded": "1548295999"
      }
    }
    

    从存储中检索字符串后,将其转换为对象并删除用户,如下所示。 (为了清楚起见,这被分解为比必要的更多的步骤。):

    let usersObject = JSON.parse(stringRetrievedFromFile);
    let userId = "780748c5d4504446bbba3114ce48f6e9";
    let userToModifyOrDelete = usersObject[userId];
    delete userToModifyOrDelete;
    

    要改为更改用户的 discordId,您可以:

    let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
    let newDiscordId = "whateverId";
    userToModifyOrDelete.discordId = newDiscordId;
    

    然后您将对象转换回字符串以存储在您的文件中:

    JSON.stringify(usersObject);
    

    希望这就是您需要了解的有关 JSON 的几乎所有信息!

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 2017-01-23
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多