Hedge Hedge - 4 months ago 17
Node.js Question

Convert & combine strings of format filter[where][id][gt] to object?

I'm sending a query-string to a server in a format resembling Loopback's Where-Filter. It's parameter are received like this:

{ 'filter[where][id][gt]': '1000',
'filter[where][price][between][0]': '7',
'filter[where][price][between][1]': '10' }


I want to turn this into a JavaScript-object for further processing.

The format I'm looking to convert it to is this:

{ where: { id: { gt: 1000 }, price: { between: [7, 10] } } }


What would be the easiest way to do so?

Are there security issues I need to keep in mind?

Answer

Using lodash you can:

var obj = { 'filter[where][id][gt]': '1000',
  'filter[where][price][between][0]': '10',
  'filter[where][price][between][1]': '7' }

var output = {};
_.keys(obj).forEach(function(key) {
    _.set(output, key, obj[key]);
});
output = output.filter; // you have the object you want.