Search code examples
node.jsreactjsarrayssequelize.jssql-order-by

Convert JavaScript array element from string to object


In React, I am trying to create the order/sort array to send to Nodejs for a situation where there we need to sort by an included table column. So, in React, I have:

sort = `[[Contact, "phone1", "asc"]]`

That is variable depending on which column header they click on in a screen, and whether descending or ascending.

In Nodejs on the backend, this shows up as a string (not an array):

sort = [ [ Contact, 'phone', 'asc' ] ]

I need it to look like this (an array AND with Contact without quotes, so that Sequelize will accept it):

sort = [ [ Contact, "phone", "asc" ] ]

so that it can be passed to Sequelize, such as:

Table.findAll({
where: {
...
},
include [ { model: Contact, ... } ]
order: sort
})

In React I can make the "Contact" have quotes around it, so that in Node I can use JSON.parse, but then Contact has quotes around it, which doesn't work when passing it to Sequelize's sort, as it thinks it is part of the original table that we are querying.

How can this be done?

Thank you very much!


Solution

  • We solved this by not passing an array from the frontend to the backend, but instead passing an object, with key-value pairs such as table, column, & direction, and then converting to an order array using sequelize.col & literals, such as...

    order: [
             [sequelize.col(`${table}.${column}`), direction]
           ]
    

    It's a bit more complicated than just this one line given all of the different possibilities in our app, but that's a good summary.

    Some notes:

    • table = the included table
    • column = the column in the included table to sort on
    • direction = 'asc' or 'desc'
    • With sequelize.col, you really don't even need to have the included table name, if there are no other column names that are the same.