Search code examples
javascriptjsonaxiosconcatenation

Adding variables to response data call in javascript


Is it possible to concatenate variable to a call to response data like so: res.data.{some_variable}?

I am using axios to call an api, I get a JSON response and in order to get some specific info I have to call each key of the object. The keys are all numbered, "object_1", "object_2", "object_3" and so on. Right now I currently have to call it as many times as the keys are, but I'm wondering if there is a better way to do it.

I have tried res.data.object_${nr} but that didn't work.

This is my code:

const path= "path_to_api";
const object_nr = this.$route.params.nodeID;
axios.get(path)
   .then((res) => {
       this.object_devices = res.data.object_1;
   })
   .catch((error) => {
       console.error(error);
   });

But I would like to be able to add the object_nr like so: res.data.object_{object_nr}


Solution

  • You can get property using index syntax:

    object['name']
    

    So you can build your own index:

    const foo = 'bar';
    object[`name_${foo}`]