J Moss
J Moss

Reputation: 205

is it possible to use a v-for in vue for non-array objects from a json file?

i am trying to pass some values from a json file to a component however i keep getting "product is undefined"

product.json

{
    "product": {
        "price": 1.11,
        "amount": 0.11
    }
}

component in vue js:

<div v-for="prod in product" :key="price">

How can i get rid of this error?

Upvotes: 0

Views: 80

Answers (2)

Shoejep
Shoejep

Reputation: 4839

If you defined product in the data of your Vue instance, you could use it within the v-for.

I've included a working version in the fiddle below.

let productJson = {
    "product": {
        "price": 1.11,
        "amount": 0.11
    }
};

new Vue({
  el: "#app",
  data: () => {
    return productJson;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(value, key) in product">{{key}}: {{value}}</div>
</div>

Upvotes: 1

Radu Diță
Radu Diță

Reputation: 14171

I'm guessing you need to loop over the keys of the object.

You can use Object.keys for this.

<div v-for="prodKey in Objects.keys(products)" :key="products[prodKey].price">

Upvotes: 1

Related Questions