Jackie
Jackie

Reputation: 23577

Searching for items in a JSON array Using Node (preferably without iteration)

Currently I get back a JSON response like this...

{items:[
  {itemId:1,isRight:0},
  {itemId:2,isRight:1},
  {itemId:3,isRight:0}
]}

I want to perform something like this (pseudo code)

var arrayFound = obj.items.Find({isRight:1})

This would then return

[{itemId:2,isRight:1}]

I know I can do this with a for each loop, however, I am trying to avoid this. This is currently server side on a Node.JS app.

Upvotes: 11

Views: 51355

Answers (6)

Pablo Ezequiel Inchausti
Pablo Ezequiel Inchausti

Reputation: 20623

You could try find the expected result is using the find function, you can see the result in the following script:

var jsonItems = {items:[
  {itemId:1,isRight:0},
  {itemId:2,isRight:1},
  {itemId:3,isRight:0}
]}

var rta =  jsonItems.items.find(
   (it) => {
     return it.isRight === 1;
   }
);

  
console.log("RTA: " + JSON.stringify(rta));

// RTA: {"itemId":2,"isRight":1}

Upvotes: 2

Jackie
Jackie

Reputation: 23577

Actually I found an even easier way if you are using mongoDB to persist you documents...

findDocumentsByJSON = function(json, db,docType,callback) {
  this.getCollection(db,docType,function(error, collection) {
    if( error ) callback(error)
    else {
      collection.find(json).toArray(function(error, results) {
        if( error ) callback(error)
        else
          callback(null, results)
      });
    }
  });
}

You can then pass {isRight:1} to the method and return an array ONLY of the objects, allowing me to push the heavy lifting off to the capable mongo.

Upvotes: 1

mathisonian
mathisonian

Reputation: 1420

edited to use native method

var arrayFound = obj.items.filter(function() { 
    return this.isRight == 1; 
});

Upvotes: 2

Bergi
Bergi

Reputation: 664930

var arrayFound = obj.items.filter(function(item) {
    return item.isRight == 1;
});

Of course you could also write a function to find items by an object literal as a condition:

Array.prototype.myFind = function(obj) {
    return this.filter(function(item) {
        for (var prop in obj)
            if (!(prop in item) || obj[prop] !== item[prop])
                 return false;
        return true;
    });
};
// then use:
var arrayFound = obj.items.myFind({isRight:1});

Both functions make use of the native .filter() method on Arrays.

Upvotes: 25

shinzer0
shinzer0

Reputation: 227

Since Node implements the EcmaScript 5 specification, you can use Array#filter on obj.items.

Upvotes: 3

3on
3on

Reputation: 6339

Have a look at http://underscorejs.org This is an awesome library.

http://underscorejs.org/#filter

Upvotes: 2

Related Questions