Use mongo style syntax to query JavaScript objects in memory from arrays instead of Mongo collections?

In mongo, I can build a query, as shown below, to return objects with a height not equal to 4 from the collection.

var mongoQuery = { height: { "$ne": 4 } }; 

But say that I have an array of objects in memory and you want to query them the same way:

 var myArr = [{height: 5}, {height: 4}, {height:3}] 

Are there existing libraries or ways to use the same syntax for arrays instead of mongo collections? For example:.

 var result = someUtil(myArr, {height: {"$ne": 4}}); //returns all objects with height != 4 

EDIT: I don't want to do != 4 , but rather generally translate from any Mongo operator (e.g. $eq , $ge , etc.)

+7
javascript mongodb
source share
2 answers

Please see sift.js. This is what you want. But use it if you really need mongodb, such as queries, otherwise use another library like lodash or underscore.

+4
source share

Checkout the underscore library.

var result = _.find(myArr, function(item){ return item.height == 4 });

+1
source share

All Articles