Skip to content
Advertisement

undefiend value in array of objects Vuejs

im trying to make an array with objects but while looping i get as a result the first 83 objects as undefiend and only the last 4 with correct data. I tried to refactor the code several times but i dont seem to find a solution.

This is the console log result i get

This is the network response i get from the API

<script>
export default {
    computed: {
        allSales(){
            var i, sales=[], x, y
            for (i = 0; i <= this.salesLists.length; i++) {
                sales[i] = {
                    x:this.date(i+1),
                    y:this.amount(i+1),
                    status:this.status(i+1),
                }
            }
            console.log(sales);// first 83 objects undefined
            return sales
        },
        salesLists() {
            this.$store.state.sale.sales
        },
    },
    methods:{
        date(id) {
            return this.salesLists.filter(sale => sale.id === id).map(sale => new Date(sale.updated_at).toISOString().slice(0,10))[0];
        },
        amount(id) {
            return this.salesLists.filter(sale => sale.id === id).map(sale => sale.amount)[0];
        },
        status(id) {
            return this.salesLists.filter(sale => sale.id === id).map(sale => sale.status)[0];
        }
    }
}

Advertisement

Answer

After looking at your second screenshot, I see that your salesLists has elements with ids greater than 87, or the length of the salesLists array. This is an issue, because in your for loop you are assuming that every element of the array has an id that is >= 1 and <= salesLists.length.

Because this is not the case, there are several iterations of the loop where your date, amount, and status methods return undefined.

I would recommend that you transform the salesLists array directly in the computed method in a single call to map. It might look something like this:

allSales(){
  return salesLists.map(sale => {
    return {
      x: new Date(sale.updated_at).toISOString().slice(0,10),
      y: sale.amount,
      status: sale.status
    }
  })
},
Advertisement