Brad
Brad

Reputation: 8678

VueJS2 sorting JSON

I have a v-for that will go through messages in a JSON response and print them to the screen. The messages come from the server in chronological order, however when I view the data via the Vue chrome add-in the data is be re-ordered alphabetically.

I have a simple example.

Here is the requested JSON via Postman:

{
    "e": "e",
    "d": "d",
    "c": "c",
    "b": "b",
    "a": "a"
}

Here is the same result when i make the call via Vue and render using v-for:

data:Object
a:"a"
b:"b"
c:"c"
d:"d"
e:"e"

So the question is, can I stop Vue from re-ordering my data? if not, how should I correctly go about re-ordering it?

Upvotes: 0

Views: 1242

Answers (1)

Roy J
Roy J

Reputation: 43881

As commenters have noted, order of keys in an object is not guaranteed, so your best option is to have your server emit messages in an ordered structure (like an array).

If that is not possible, I have found that key order is generally preserved in an object created all at once (like your JSON data). Object.keys(data), will give you an array of keys that is likely in the original order.

So instead of something like

<div v-for="value in data">

do

<div v-for="key in Object.keys(data)">

and then use data[key] to get the value.

You can also try Object.entries depending on whether you need IE support.

If this is going to be widely deployed, expect it to break for somebody sometime. If you just need something that works for you, this could do it.

Upvotes: 2

Related Questions