Aldo
Aldo

Reputation: 1287

Is this the best way to transform a string into an object in Node.js?

The code below is working, however, I think it is a lot of coding. I am uncomfortable with this. Does someone know a more concise way to write this?

The main goal is extracting a sort param from a HTTP query and sort a Mongoose/Mongodb collection.

The sort query is GET /flavors?sort=id ASC, so, I took this string ["id", "ASC"] in sort and transformed it in {id : ASC} in sortStr

router.get("/", (req, res) => {
      var { sort } = req.query;
      var v_fields = sort.split(",");
      var v_field = v_fields[0].replace('[', '');
      var v_order = v_fields[1].replace(']', '');
      var sortStr = `{ ${v_field} : ${v_order} }`;
      var re = new RegExp(`"`, 'g');
      sortStr = sortStr.replace(re, '');

      Flavor.find().sort(sortStr).then(result => {
...
}

Upvotes: 0

Views: 51

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Yes there is:

 const [key, order] = req.query.sort.split(" ");
 Flavor.find().sort({ [key]: order }).then(/*...*/);

Concerning your code:

1) vfields is an array, and the arrays elements do not contain any [ or ] in your example so there is no need to remove them.

2) sort expects an object, so you should pass an object not a string.

Upvotes: 0

sbrass
sbrass

Reputation: 995

If I understand you correctly, and your sort string always represents an array containing two elements, you could do something like this:

var s='["id", "ASC"]';
var arr=JSON.parse(s);
var sortObj={};
sortObj[arr[0]]=arr[1];

Upvotes: 1

Related Questions