vue js DO NOT sort array by keys

I have made a shopping cart with vue js and want to keep products displayed in the order they have entered. The problem is the products are associative arrays with their id’s used for keys something like [1 => ['name' => 'product1', 'price' => 100', 'quantity' => 1]] Where the key 1 is the id of the product. The problem is when I return the cart object as json that the products array is ordered by default by view by it’s keys. Here’s my code:

let app = this 
axios.post(app.addToCartRoute, {
    _token: '{{ csrf_token() }}',
    product_slug: slug
})
.then(function(response) {
    if(!app.showCart) {
        setTimeout(() => {
           app.cart = response.data
        }, 250)
    }
    else {
        app.cart = response.data
    }
        app.showCart = true
        console.log(response.data)
})
.catch(function(error) {
    console.log(error)
})

Let’s say I first add product with id 3 to the cart the array looks like this: [3 => ['name' => 'product3', 'price' => 15.00]] and then I add product with id 1 the array starts looking like this: [1 => ['name' => 'product1', 'price' => 13.00], 3 => ['name' => 'product3', 'price' => 15.00]] I dont want that but vue js seems to order them by default. How to avoid that?

Answer

Borrowing from another stackoverflow answer:

Javascript doesn’t have “associative arrays” the way you’re thinking of them. Instead, you simply have the ability to set object properties using array-like syntax, plus the ability to iterate over an object’s properties.

The upshot of this is that there is no guarantee as to the order in which you iterate over the properties

In other words, Vue does not reorder your data. Rather, response.data is an object, and Javascript objects do not have the same concept of “order” as PHP associative arrays.

If the ordering of products is important, then you should associate each product with a position. Then, to display them, you can order them using that positional information.

Leave a Reply

Your email address will not be published. Required fields are marked *