javascriptsqljsobject

How to convert a sql return to a custom Object?


In my code I make a SELECT on an SQL table where parameters are stored and I would like to output an OBJECT in this way:

{
  inscription_max: 0,
  inscription_open: false,
  liste_attente_max: 0
}

SQL Return :

[
  RowDataPacket { setting: 'inscription_max', value: '0' },
  RowDataPacket { setting: 'inscription_open', value: 'false' },
  RowDataPacket { setting: 'liste_attente_max', value: '0' } 
]

If you need more information, don't hesitate. I hope you can help me.

Thank you in advance.


Solution

  • You can try reduce for an array that will add a new field to resulting object for every array element : smth like this

    let data = [
      { setting: 'inscription_max', value: '0' },
      { setting: 'inscription_open', value: 'false' },
      { setting: 'liste_attente_max', value: '0' } 
    ]
    
    data.reduce((acc, rec) => ({...acc, [rec.setting] : rec.value}), {})