0

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.

1
  • channels is not an array. Commented Jan 22, 2021 at 12:51

1 Answer 1

2

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] )
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.