Bobosky
Bobosky

Reputation: 167

writeFile output issues. Didn't show what I expected to see

I don't understand how can I write the file like this:

{
    "726623241984278589": {
        "322366672625467392": {
            "Moderation": "Kick",
            "Target": "Bobo#1601",
            "Moderator": "Bobosky#3914",
            "Reason": "Testing",
            "ID": "#XLR6RV8M"
        }
    }
}

Here is the my code of fs.writeFile:

const TargetMemberID = TargetMember.id

data[message.guild.id] = {
    TargetMemberID: {
        Moderation: 'Kick',
        Target: `${TargetMember.user.tag}`,
        Moderator: `${message.author.tag}`,
        Reason: `${Reason}`,
        ID: `#${ID}`
    }
}

fs.writeFile("./data.json", JSON.stringify(data), (err) => {
    if (err) console.log(err);
});

but it out put like this:

{
    "726623241984278589": {
        "TargetMemberID": {
            "Moderation": "Kick",
            "Target": "Bobo#1601",
            "Moderator": "Bobosky#3914",
            "Reason": "Testing",
            "ID": "#XLR6RV8M"
        }
    }
}

so this is not what I expected to see. I want to see the TargetMemberID above replaced by the number just like what I expected as the first json code. Any clue on it?

I've tried making the writing part as

data[message.guild.id[TargetMember.id]]

but it doesn't work.

PS : I didn't put all my codes such as the definding part of TargetMember, Reason etc. All of those are based on discord.js.

Upvotes: 2

Views: 37

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23160

In JavaScript, object keys are strings, so when you write TargetMemberID as key, it's the same as writing "TargetMemberID". If you want the key to be the value of TargetMemberID, you need to add square brackets around it. And this way you could also just use TargetMember.id, you don't need a new variable for this.

Also, you don't need to use template literals in those values, you can just pass them as below.

data[message.guild.id] = {
    [TargetMember.id]: {
        Moderation: 'Kick',
        Target: TargetMember.user.tag,
        Moderator: message.author.tag,
        Reason: Reason,
        ID: ID,
    }
}

You could also use the shorthand syntax, when the object key and the variable is the same:

data[message.guild.id] = {
    [TargetMember.id]: {
        Moderation: 'Kick',
        Target: TargetMember.user.tag,
        Moderator: message.author.tag,
        // same as Reason: Reason
        Reason,
        // same as ID: ID
        ID,
    }
}

Upvotes: 1

Related Questions