BackspaceRGB
BackspaceRGB

Reputation: 19

How do I loop through a JSON array?

I have a Discord.js bot, I wanted to make a lockdown command, but my channel ids are stored in a JSON file, and I dont know how to iterate through it. This is the JSON configuration:

{
    "channels": {
        "main": {
            "id": "691548147922763825"
        },
        "creations": {
            "id": "700390086390448148"
        },
        "fanart": {
            "id": "691551615873843211"
        },
        "memes": {
            "id": "691549417173680148"
        }
    }
}

How can I loop through it? I know that just doing forEach on a JSON file doesnt work, so I need some help.

Upvotes: 0

Views: 1076

Answers (1)

Rob Monhemius
Rob Monhemius

Reputation: 5144

You can use for..in loops on objects to get the keys and iterate over them. Objects don't implement the Iterable interface, so for...of doesnt work. And forEach is not a method on an object, but on an array.

const json = {
    "channels": {
        "main": {
            "id": "691548147922763825"
        },
        "creations": {
            "id": "700390086390448148"
        },
        "fanart": {
            "id": "691551615873843211"
        },
        "memes": {
            "id": "691549417173680148"
        }
    }
}

for( let key in json.channels ) {
  console.log( key, json.channels[key] )
}

Upvotes: 2

Related Questions