I need help trying to recurse through this JSON object to build a query. I am doing so in JavaScript.
NodeJS
I have an object that looks like this
{
type: "and",
left: {
type: "eq",
left: {
type: "property",
name: "City"
},
right: {
type: "literal",
value: "Seattle"
}
},
right: {
type: "and",
left: {
type: "eq",
left: {
type: "property",
name: "State"
},
right: {
type: "literal",
value: "Washington"
}
},
right: {
type: "and",
left: {
type: "eq",
left: {
type: "property",
name: "FirstName"
},
right: {
type: "literal",
value: "John"
}
},
right: {
type: "eq",
left: {
type: "property",
name: "LastName"
},
right: {
type: "literal",
value: "Doe"
}
}
}
}
};
Here is some of the code. The object above will be passed into the filter method below as querySchema.
I have been trying many different recipes to getting this to get this done. This is different from any recursion I have ever done.
var QueryBuilder = Class({
constructor: function (model) {
this.model = new model();
},
filter: function (querySchema) {
var self = this;
// recurse somewhere in here and run the conditions below somewhere in the midst
// of the recursion.
if (querySchema.hasOwnProperty(property)) {
if (property == 'type' && querySchema[property] == 'and') {
self.filter(querySchema.left);
}
if (querySchema.type == 'eq') {
this.model.where(querySchema.left.name).equals(querySchema.right.);
}
if (querySchema.type == 'gt') {
this.model.where(querySchema.left.name).gt(querySchema['right']);
}
if (querySchema.type == 'lt') {
this.model.where(querySchema.left.name).lt(querySchema['right']);
}
}
}
});
Any help is very much appreciated.
Class, what ismodel, what are thosewheremethods? How would one compare properties against each other, are there any other types - what is the schema of your json?type : 'or'allowed? Then you would want to make sure you handle it correctly.