1

Is there a way to use a template literal as an object identifier? Here's an example I've been working on

  const [courses, setCourses] = useState([]);
  const [search, setSearch] = useState({
    searchTerm:'',
    catagory: '',
  });

  const searchChange = (e) => {
    setSearch(e.target.value);
    console.log(search);
  };

useEffect(() => {
    const axios = axiosWithAuth();
    axios
      .get(`https://anywhere-fitness-wpt199-be.herokuapp.com/api/courses`)
      .then((res) => {
        console.log("getCourses results", res);
        const pulledArray = res.data;
        const filteredArray = pulledArray.filter((options) => {
return options.`${search.catagory}`.includes(search.searchTerm.toLowerCase());
        })
        setCourses(filteredArray);
        console.log(courses);
      })
      .catch((err) => console.log(err));
    },[search])

I've tried a few different options and can't seem to find anything online about it.

I'm trying to set my identifier to the value of the catagory key, which will in turn be determined by the user.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

1

You don't need a template literal for this just try like so

const filteredArray = pulledArray.filter((options) => {
   return options[search.catagory].includes(search.searchTerm.toLowerCase());
})
caramba
  • 21,963
  • 19
  • 86
  • 127
  • thanks for taking the time to reply. looks like i didn't explain well enough what I'm trying to accomplish. let me update it and see if i can explain a little more – Simple Zack Apr 28 '21 at 20:41