Problem to updating mysql table with array of object js

(Celebrating my first post on Stackoverflow 🥳)

I have a personal project using React.js for front-end, Node.js/express for back-end and my database is mySQL.

I have this array :

horaires = [
  { jour: 'Lundi', horaire: 'Fermé' },
  { jour: 'Mardi', horaire: 'Fermé' },
  { jour: 'Mercredi', horaire: 'Fermé' },
  { jour: 'Jeudi', horaire: 'Fermé' },
  { jour: 'Vendredi', horaire: 'Fermé' },
  { jour: 'Samedi', horaire: 'Fermé' },
  { jour: 'Dimanche', horaire: 'Fermé' }
]

And I would like to update my "horaires" table with these news values.
This table looks like this :

+----+----------+-----------+
| id | jour     | horaire   |
+----+----------+-----------+
|  1 | Lundi    | Fermé     |
|  2 | Mardi    | 18h - 21h |
|  3 | Mercredi | 18h - 21h |
|  4 | Jeudi    | 18h - 21h |
|  5 | Vendredi | 18h - 21h |
|  6 | Samedi   | 18h - 21h |
|  7 | Dimanche | Fermé     |
+----+----------+-----------+

I tried to TRUNCATE then INSERT, I tried to UPDATE…
I tried to formate my array with reducer to use it in my request :

  const newHoraires = horaires.reduce((acc, current, index) => {
    const newArray = [];
    newArray.push(index);
    newArray.push(current.jour);
    newArray.push(current.horaire);
    acc.push(newArray);
    return acc;
  }, []);

// Output => newHoraires [
  [ 0, 'Lundi', 'Fermé' ],
  [ 1, 'Mardi', 'Fermé' ],
  [ 2, 'Mercredi', 'Fermé' ],
  [ 3, 'Jeudi', 'Fermé' ],
  [ 4, 'Vendredi', 'Fermé' ],
  [ 5, 'Samedi', 'Fermé' ],
  [ 6, 'Dimanche', 'Fermé' ]
]

I have this error most of the time : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘0, ‘Lundi’, ‘Fermé” at line 1.

How can I formate my array to TRUNCATE and then INSERT ? Or UPDATE my current table with new values ? What would be the best practice ?

Thanks in advance for your help…

>Solution :

Use map(), not reduce().

const newHoraires = horaires.map(({jour, horaire}, index) => [index, jour, horaire])

Leave a Reply