Home > Enterprise >  how can i access json data using for loop in vue js
how can i access json data using for loop in vue js

Time:10-01

This is my template:

  <div
      v-for="product in order.products"
            :key="product._id"
          >
      {{product.productID.brand}}
  </div>

If I replace {{product.productID}} with {{product.productID.brand}} returns this json

  {
      _id: "631a90d3fd9c107baa1bc716",
          brand: "nike"
  }

I'm trying to access product.productID.brand but i'm getting this error in my console

vue.runtime.esm.js?c320:3020 TypeError: Cannot read properties of null (reading 'brand')

this is my script tag

<script>
import axios from "axios";
export default {
  name: "Products",
  data() {
    return {
      products: [],
      orders: ""
    };
  },

  mounted() {
    axios
      .get("http://localhost:5000/api/orders", {
      })
      .then(res => {
        console.log(res);
        this.orders = res.data.products;
      })
      .catch(err => {
        console.log(err);
      });
  }
};
</script>

CodePudding user response:

It is possible that product.productID is null and you are trying to access brand from null which is causing error. To avoid error, you can use optional chaining

product.productID?.brand
  • Related