从js中的json表删除用户

时间:2019-01-24 17:42:08

标签: javascript arrays node.js json

所以我是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不太了解

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这是为您准备的快速教程: 您可以选择“用户”是数组(使用[])还是javascript对象(使用{})。除非使用数据库而不是JSON文件,否则不会有任何实际的表(尽管如果JSON表达式与示例一样简单,则几乎可以将其视为表。)-实际上,第三个选择将使用javascript Map类型,这类似于功能更强大的对象,但在此我不会解决。

虽然使用数组会使 all 用户的数据列表检索变得容易一些(因为数组更易于迭代),但是使用对象会使检索数据变得更加容易对于一个单个用户(因为您可以通过其键直接指定所需的用户,而无需遍历整个数组直到找到所需的那个用户。)我将向您展示一个示例,使用一个对象。

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

要符合JSON格式,可以按以下方式构造Users对象。 (当然,我们正在查看字符串化版本,因为仅仅人类无法轻易读取“实际的” 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!

答案 2 :(得分:0)

在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});

    })
}