skip to Main Content

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


  1. There’s a simple solution with Array#reduce() and nullish coalescing assignment:

    const data = [{id: '1', date: '2024-05-05', start: '1', description: 'fdsfdsfd', standort: 'sz'}, {id: '2', date: '2024-05-05', start: '1', description: 'fdsfdsfd', standort: 'sz'}];
    
    class Event{
      constructor(data){
        Object.assign(this, data);
      }
    }
    
    const result = data.reduce((r, {date, id, ...rest}) => ( (r[date]??={})[id] = new Event(rest), r ), {});
    
    console.log(result);
    Login or Signup to reply.
  2. 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 id

    The 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

    $lbtbs = $DB->get_records('lbtb_eintraege', null, 'date,id', 'id,date,start,description,standort');
    

    See https://moodledev.io/docs/4.4/apis/core/dml#get_records

    Then convert the array to your requirements in PHP

    $data = array();
    
    foreach ($lbtbs as $lbtb) {
        $data[$lbtb->date][$lbtb->id] = array($lbtb->start, $lbtb->description, $lbtb->standort);
    }
    

    Then convert to json

    $lbtb_json = json_encode($data);
    

    Also note: date is a reserved word and shouldn’t be used for a column name

    See https://docs.moodle.org/dev/XMLDB_reserved_words

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search