Home > database >  I needed to make a list in Javascript, but to no avail
I needed to make a list in Javascript, but to no avail

Time:01-11

I'm using an API and I wanted to extract the API URLs, for this I made a code, but only a url appears, I will give example of the JSON code of the API. Not to mention that a title comes, then comes in order first title and then the URL

{
 "items": [
     { "title":"YouTube", "url":"https://www.youtube.com/"}, 
     { "title":"Google", "url":"https://www.google.com/"},
     { "title":"Facebook", "url":"https://www.facebook.com/"},
     { "title":"Github", "url":"https://www.github.com"},
     { "title":"Microsoft", "url":"https://www.microsoft.com"}
 ]
}

It's not exactly these urls, I used it as an example.

I would like to extract this information and leave as follows:

[Title](Url)

I want it to look like this, because the title will turn blue and when you click it goes to the site URL.

My code that didn't work out is this:

        let response, channel, info;

        try {
            response = await axios.get(url)
            channel = response.data
            info = channel.items[0]
        }  catch (e) {
            return message.channel.send(`Error`)
        }

  let btn = new disbut.MessageButton()
     .setLabel("Site")
     .setStyle("url")
     .setURL("https://youtube.com")

        const embed = new MessageEmbed()
            .setColor("#ffff00")
            .setDescription(`[${info.title}](${info.url})\n`)

        await message.channel.send({
          embed: embed,
          buttons: btn
          });

This info.url is where you get the URL and info.title is where you get the title, only there's only 1 problem, it takes only 1 title and 1 url, I would like you to take them all and form a list in The Discord Bot

This is the result of the code:

But I wanted it to look like this: Youtube Google Facebook Github Microsoft

So that only youtube appears I need you to show at least 1 and a maximum of 10. And when you click on each title, be redirected to the site.

CodePudding user response:

info only refers to channel.items[0], which is the first item

You can use <Array>.map to map the items into your []() format and then <Array>.join to concatenate them into a string separated by newlines.

.setDescription(channel.items.map(info => `[${info.title}](${info.url})`).join('\n'))

CodePudding user response:

You need to format the items array as a Markdown list.

Map the channel.items array to an array of list item strings, then join the entire thing together with newlines.

.setDescription(
  channel.items.map(info => `* [${info.title}](${info.url})`).join("\n")
)
  •  Tags:  
  • Related