Home > Enterprise >  Convert JavaScript array element from string to object
Convert JavaScript array element from string to object

Time:11-05

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!

CodePudding user response:

Contact is without quotes because the Contact is reference to the actual class definition which is being used in the frontend. When you send your request to the backend then this class information is lost.

Even if there is a class with the same name on the backend, it cannot be converted to that class definition just by the same name. You should include for example a middleware (if you are using express for example) that replace your stringified "Contact" with an actual definition that Sequelize can use.

Something like this on the server:

const Contact = required('./your-path-to-contact')

// ...some other stuff happening...

sort.forEach(s => {
  if(s === 'Contact') 
    s = Contact
})

This solution is a little bit hacky but can work. For a good solution I would refrain from sending class to the server. I would rather have some kind of query builder which the server understands and can select the appropriate class to use when the time comes.

CodePudding user response:

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.
  • Related