How can I dynamically use a variable to destructure an object of various objects

424 Views Asked by At
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 ?

0

There are 0 best solutions below