Nivyan
Nivyan

Reputation: 139

How to display JSON keys in Vue.js?

I have some JSON which looks like this:

    {
    "data": [
        {
            "name": "someName",
            "link": "http://somelink.com",
            ],
            "relevantArray": [
                {
                    "keyIWant": 42
                }
            ],
            ...
     }

and I get the data like this:

<li v-for="(dataVue, index) in dataList.feat" :key="index">
          {{ dataVue.someName }}
          {{ dataVue.link}}
          {{ dataVue.??? }}
</li>

what do I write to return keyIWant - the name of the key, not the value (42)??

EDIT: I can output the JSON by writing

{{dataVue.relevantArray}}

But this returns the JSON like this:

[ { "relevantArray": keyIwant } ]

and I just can't get the relevantArray to return by itself. CodeSandbox:

https://codesandbox.io/s/festive-wu-41kyz?file=/src/App.vue

Upvotes: 0

Views: 1887

Answers (2)

Nivyan
Nivyan

Reputation: 139

Arief' answer didn't solve the problem for some reason, but I played around with it and found the following solution:

<span
     v-for="(r,ri) in vueData.relevantArray[0]" :key="ri">
      {{ ri }} ==> {{ r }}
         <span v-for="(arrayData, index) in r" :key="index">
            {{index}}
         </span>
   </span>

This makes the output I wanted, doing the above solutions outputted the array in my case. I'll mark Arief' solution as the answer, as it lead me to my solution.

If anyone want to tell me why I had to do my version, I'd be very grateful.

Thanks everyone!!

Upvotes: 0

Arief Darmawan
Arief Darmawan

Reputation: 309

Try this https://codesandbox.io/s/mystifying-brook-42m3x

Basically you can iterate any object as key-value using v-for

<li v-for="(vueData, index) in vueData.data" :key="index">
  {{ vueData.someName }}
  {{ vueData.link }}
   <span
     v-for="(r,ri) in vueData.relevantArray[0]"
     :key="ri"
     >{{ ri }} ==> {{ r }}
   </span>
</li>

will give you something like this

someName http://somelink.com keyIWant ==> 42

Upvotes: 3

Related Questions