0

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];
        }
    }
}
2
  • 1
    It looks like you're trying to use map on the object returned by filter in your methods. Why are you doing this? Commented Sep 22, 2020 at 23:10
  • In your allSales() computed property, you aren't actually doing anything with the data contained in salesLists, you're simply using its length. Is this intentional? Commented Sep 22, 2020 at 23:14

1 Answer 1

1

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
    }
  })
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.