1
export const apiDataDay = async () => {
  try {
    var days = [
      "monday",
      "tuesday",
      "wednesday",
      "thursday",
      "friday",
      "saturday",
      "sunday",
    ];
    var date = new Date();
    var dayName = days[date.getDay()-1];
    console.log("Today's Day is", dayName);
    console.log("Today's DayNumber is", date.getDay()-1);


// I want to do the following:-
//   const { data : {dayName} } = await axios.get(`${url}/schedule/${dayName}`);
// The API's works like this
//https://api.jikan.moe/v3/schedule/tuesday
// data: {tuesday : {............}}
//https://api.jikan.moe/v3/schedule/wednesday
// data: {wednesday : {............}}
//https://api.jikan.moe/v3/schedule/saturday
// data: {saturday : {............}}


    const { data } = await axios.get(`${url}/schedule/${dayName}`);
    console.log(data);
    return data;
  } catch (error) {
    console.log(error);
  }
};

I want to use the variable dayName to destructure the data object from the array as the API changes dynamically, so I want to access the data in the dynamic manner too.

I want to access the API's data object dynamically , {data :{dayName}} , where I can destructure the api data object according to the day, will fullfil it. What is the best way to achieve this ?

Abdullah Ch
  • 1,678
  • 1
  • 13
  • 31
  • `const { data: {[dayName]: val} } = ...` should do what you're after, where `val` is set to the value at the dayName key – Nick Parsons Sep 19 '20 at 07:57
  • 1
    Yes, it did what I wanted ! Can you tell me the reason/logic behind [dayName] : day ? Thank you ! – Abdullah Ch Sep 19 '20 at 08:02
  • 1
    The `[]` around a key name is a special syntax known as [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015). Rather than using `dayName` as the key, it uses the _value_ of `dayName` as the key (the expression between the [ and ] is evaluated first which is then used as the key), and can also be used in destructuring assignment. – Nick Parsons Sep 19 '20 at 08:23

0 Answers0