1

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.

Antonin_04
  • 37
  • 5

2 Answers2

1

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}), {})
elvira.genkel
  • 1,303
  • 1
  • 4
  • 11
0

You can .map() each object to a variant of the current object, where the setting value is the key of the new object and the value of the value property is the value of the new object. You can also use JSON.parse(value) to ensure its string version is parsed to its primitive value (see second example). Then you can use Object.assign() with the spread syntax to build an object from your new array of objects:

const arr = [
  { setting: 'inscription_max', value: '0' },
  { setting: 'inscription_open', value: 'false' },
  { setting: 'liste_attente_max', value: '0' } 
];

const res = Object.assign({}, ...arr.map(({setting, value}) => ({[setting]: value})));
console.log(res);

If you can support Object.fromEntries(), the same result can be achieved with a little less code:

const arr = [
  { setting: 'inscription_max', value: '0' },
  { setting: 'inscription_open', value: 'false' },
  { setting: 'liste_attente_max', value: '0' } 
];

const res = Object.fromEntries(arr.map(({setting, value}) => [setting, JSON.parse(value)]));
console.log(res);

The above can be written more elegantly, as pointed out by @Andreas:

const arr = [ { setting: 'inscription_max', value: '0' }, { setting: 'inscription_open', value: 'false' }, { setting: 'liste_attente_max', value: '0' } ];

const res = Object.fromEntries(arr.map(Object.values)); // credit to: @Andreas
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64