Search code examples
javascriptvue.jswebaxioslodash

Vue JS - Loop through nested object without knowing its name


I perform an axios call which returns the following (example):

{
   "data":{
      "xyz":[
         {
            "foo":1234,
            "baz":5678,
         }
      ]
   }
}

I have a .then() in my axios call where I use lodash to _.cloneDeep my response.data (above) to a data property in my vue instance.

What is the right way to do a v-for on xyz without knowing it's name (it can be different)? Or how do I directly clone xyz to my data property?


Solution

  • To directly clone xyz to your data property, you can just do (assuming response.data contains that snippet that you gave in your question:

    dataPropertyInVueInstance = response.data["data"][Object.keys(response.data["data"])[0]]
    

    This gets the first key at response.data["data"] (in this case, xyz) and pulls the data there out of response.data["data"], thus giving you the object at xyz and avoiding the naming issue.

    You could also do:

    dataPropertyInVueInstance = Object.values(response.data["data"])[0]
    

    This gets the value at the first key in response.data["data"] -- in this case, the data at key xyz.