I need a different order of the values of my JSON string.
I use php to create a JSON string from a database query that looks like this:
$lbtbs = $DB->get_records('lbtb_eintraege');
$lbtb_json = json_encode($lbtbs, JSON_PRETTY_PRINT);
The database is read out in the “Moodle” system.
According to the documentation an array of objects is returned.
My JSON string that I submit using php looks like this:
{id: '1', date: '2024-05-05', start: '1', description: 'fdsfdsfd', standort: 'sz', …}
In Javascript I parse the JSON string with:
this.events = JSON.parse(decodeURI(this.lbtbdata));
However, I need the string to be nested differently. The date should come first, then the ID and the remaining values within the ID.
As an example:
[DATE]
- [ID]
- [REST DATA]
I tried it like this.
for (const date of Object.keys(this.events)) {
for (const id of Object.keys(this.eventsMay 6, 2024)) {
const event = new Event(this.eventsMay 6, 2024[id]);
this.eventsMay 6, 2024[id] = event;
}
}
I’m still missing a few exercises when it comes to JavaScript. I would therefore be grateful for any suggestion for a solution or for a few keywords to search for!
2
Answers
There’s a simple solution with
Array#reduce()
and nullish coalescing assignment:It would be more efficient to let the server do the work rather than on the client side
The third parameter for
get_records
is a sort, so you could sort by date and idThe fourth parameter is a list of field names, so you could specify the field names if you don’t need them all – the first field needs to be a unique value though, the date might not be a unique
See https://moodledev.io/docs/4.4/apis/core/dml#get_records
Then convert the array to your requirements in PHP
Then convert to json
Also note:
date
is a reserved word and shouldn’t be used for a column nameSee https://docs.moodle.org/dev/XMLDB_reserved_words