Home > Net >  Response.data how to get a single data value
Response.data how to get a single data value

Time:03-29

Here is the code that im using to try get a single element out of the data.response of an api:

client.on("message", msg => {
  var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://dad-jokes.p.rapidapi.com/random/joke',
  headers: {
    'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
    'X-RapidAPI-Key': '0f787e5af5msh468814e0b585173p1cacafjsn7d774dfb44ff'
  }
};
  if(msg.content === "daddy"){
    axios.request(options).then(function (response) {

      console.log(response.data);
      let dataDad = response.body
        msg.channel.send(`${dataDad}`)
  })`

and here is the response that i get from the api:

{
  success: true,
  body: [
    {
      _id: '60dd3729df8a37528bc79b03',
      setup: 'How often do scientists check the table of elements?',
      punchline: 'Periodically',
      type: 'periodical',
      likes: [],
      author: [Object],
      approved: true,
      date: 1618108661,
      NSFW: false
    }
  ]
}

How do I use the "setup" from the response data in my code at msg.channel.send( "the "setup" ) ?

CodePudding user response:

I believe, You need to do response.data.body[0].setup in order to get the first objects setup property

msg.channel.send(response.data.body[0].setup);

CodePudding user response:

response.data.body is an array of objects. So, if you want to access the first object in that array, you would use response.data.body[0] So, to get the .setup property from that object, you would use this:

msg.channel.send(response.data.body[0].setup);

That will get you the setup property from the first object in the response.data.body array.

  • Related