J
J
JohnDaniels2017-05-31 00:16:47
API
JohnDaniels, 2017-05-31 00:16:47

How can I deal with json sorting?

Help, my head is already spinning.
Task: get from the server and display an array of data sorted by a specific field.
The server is running laravel, the client is vuejs (if that matters).
on the server I do this:

echo json_encode([
            'log'  => Log::all()->sortByDesc('id')->toArray()
        ]);

where id is the autoincrement in the database. That is, I just need to display the data in reverse order.
Then I don't understand what's going on. I send the request simply by the browser:
6ecb3fc1c43545c8b3b4323f60e94126.png
That is, on the browser screen, the response is sorted correctly, from largest to smallest. But the console does not see this sorting.
And on the client, I do
this.log = response.body.log
and get this.logdata from the console, that is, in the wrong sort.
Which way to think?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nik Gubin, 2017-05-31
@JohnDaniels

In this case, it is not backend and laravel that are to blame, but your gap in the basics of js, no offense))
Conduct an experiment and execute the code:

var obj = {2:"два", 1:"один", 10:"десять", 0:"нуль"};
console.log(obj);

In whatever order we place records with a numeric key inside the object, they will be sorted from smallest to largest when output (because, as it was rightly noted in the comments above, the object is not sorted, and the keys are set in order).
Do you want to keep order? Cast the key to the string, but a simple string with a number will not save, JS will first convert it to a number anyway and sort it again. You can add any string character to the key and the entries will eventually retain their order.

A
Alex Wells, 2017-06-01
@Alex_Wells

I subscribe to Nik Gubin 's solution , but there is another option: sorting on the client =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question