Trupti
Trupti

Reputation: 983

How to read json object in vuejs?

Following is my json object:

const faqs = [{'question1':'answer1'},{'question2':'answer2'}]

I am reading this in vuejs in for loop in div as

<div v-for="(value, name, index) in faqs" :key="index">{{ value}}::{{ name }}</div>

but I not getting the required result.

Please guide me what am I doing wrong?

Following is the console log: enter image description here

Thank you, Trupti

Upvotes: 0

Views: 454

Answers (1)

holmicz
holmicz

Reputation: 577

In this cycle you are iterating over the faqs array, that means, it goes over each contained object one by one. The cycle does not go into objects, for that, you need separate cycle.

In addition to that, your data are not well formed, try to transform them to following:

[{ question: "question 1", answer: "answer 1"}, {question: "question 2", answer: "answer 2"}]

After that you can do:

<div v-for="(value, index) in faqs" :key="index">{{ value.question}}::{{ value.answer }}</div>

This will yield result:

question 1::answer 1
question 2::answer 2

On the other hand if you really want to iterate over properties of contained objects, then you need to do something like:

<div v-for="(value, index) in faqs" :key="index">
    <div v-for="(propValue, propName) in value">
    {{propName}}::{{propValue}}
</div>

This will work for the data in the original form you have posted. You have first cycle, which goes through each object (question-answer pair) one by one and second nested cycle, which goes over properties of every object.

Upvotes: 2

Related Questions