0

I'm new to NodeJS and I'm trying to learn it a bit better by writing a Discord bot. But I'm having an issue with stringifying an object to JSON. I think it's having an issue with the array I'm setting, but I'm not sure how else I would do this. If I'm not supposed to set an array and using my guildMembers example below, how else should I insert this data into my JSON file?

I've looked through a few examples here on StackOverflow and found this particular article: JSON Stringify Removing Data From Object. However, it's not clear to me given what I'm trying to achieve.

    var o = {};
    var guildKey = guild.id;
    o[guildKey] = [];
    o[guildKey]['guildMembers'] = {};
    var guildMembers = []
    guild.members.forEach(function(guildMember, guildMemberId) {
        if (!guildMember.user.bot){
            var memberData = {
                id: guildMember.id,
                data: {
                    userName: guildMember.user.username,
                    nickName: guildMember.nickname,
                    displayName: guildMember.displayName,
                    joinedAt: guildMember.joinedAt
                }
            }

            guildMembers.push(memberData);
        };
    });
    o[guildKey]['guildMembers'] = guildMembers;
    json = JSON.stringify(o);

I am expecting the data to show the guildMembers object with the array under the guildKey object. However, the JSON shows only the guildKey object with an empty array:

{"guildKey":[]}

2 Answers 2

1

You make guildKey an array and then try to use it as an object ... Solution is:

o[guildKey] = {};

Just like in the mentioned post.

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers mate ! I recommend MDN documentation for the "little" things. Plays out well in the long run.
1

It is because you are assigning a key-value pair to an array with

o[guildKey]['guildMembers'] = { }; <= o[guildKey]

When iterating over an array to display the contents, JavaScript does not access non-integer keys. You should store o[guildKey] as an object instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.