0

I have a json file called "GuideDB" which contains data about somethings.

GuildDB.json
{"GuideID":{"prefix":"","DJ":null,"Roles":""}}

Basically I want to access the data "Roles" in a way I can manage each element in that line, e.g.:

const myArray = GuildDB.Roles; //GuildDB.Roles is the only way to access that line.
myArray.forEach(element => { 
     console.log("<@&" + element + ">") 
});

this code gives the error "forEach", because the array is not correctly formated.

How do I add Items in GuildDB.Roles?

    client.database.guild.set(message.guild.id, {
      prefix: GuildDB.prefix,
      DJ: GuildDB.DJ,
      Roles: GuildDB.Roles + ", " + createdRole.id, //Bug: First run always writes the comma first.
    });

This will result the following:

{"GuideID":{"prefix":"","DJ":null,"Roles":", 123, 1234, 12345, 123456"}}

Which is not what I want.. and I don't care how this looks, I need to make it easy access to read/manage that data of Roles.

Hope anyone can help..

Zuher Laith
  • 27
  • 1
  • 2
  • 10
  • 1
    There is no array here. The `Roles` key has a string assigned to it, you cannot call `forEach` on a string. Although, I'm not really convinced you are accessing the correct `Roles`, I suspect you're actually getting `undefined` out because you're supposed to do `data.GuideID.Roles`, otherwise you get it from the top level object which only has a `GuideID` key. See [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383) – VLAZ Sep 08 '21 at 13:37
  • @VLAZ Now I understand now this is a object not an array, but I don't have much knowleadge in this, I wanted to figure out the correct way of adding a **value** not an entire **key** inside Roles, and being able to read/check/delete one of them like an array.. can you provide an example please? – Zuher Laith Sep 08 '21 at 13:51
  • Somewhat unrelated, but JSON is a poor choice for a database for DJS, consider using a proper db in the future – Elitezen Sep 08 '21 at 14:21

1 Answers1

1

You can do something like this to convert Roles into array first and then use forEach loop on it.

const myArray = GuildDB.Roles.split(",");

krunal
  • 60
  • 5
  • That worked absloutely smooth, and it outputed as an array just the way I want.. But what if I wanted to remove a specific value of it? and the Roles is now like **"Roles":"123,1234,12345"** is it manageably easy? – Zuher Laith Sep 08 '21 at 14:00
  • yes it will mangable easily if your string is like *"123,1234,12345"* after converting to array you can use filter method to remove specific value from it – krunal Sep 09 '21 at 07:24