11

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.

Jackie
  • 21,969
  • 32
  • 147
  • 289
  • Unless you have more info, iteration is unavoidable. But why are you trying to exclude that anyway? – Zirak Aug 06 '12 at 21:18
  • What do you mean by "*without iteration*"? How could that work? – Bergi Aug 06 '12 at 21:25
  • I suppose I meant without the tradition itteration pattern (a regular for each loop) But I am sure the is some creative use of regex and/or mapping that could be used as well. – Jackie Aug 06 '12 at 23:24

6 Answers6

25
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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

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

shinzer0
  • 227
  • 2
  • 6
2

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

http://underscorejs.org/#filter

3on
  • 6,291
  • 3
  • 26
  • 22
2

edited to use native method

var arrayFound = obj.items.filter(function() { 
    return this.isRight == 1; 
});
mathisonian
  • 1,420
  • 13
  • 17
2

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}
Pablo Ezequiel Inchausti
  • 16,623
  • 7
  • 28
  • 42
1

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.

Jackie
  • 21,969
  • 32
  • 147
  • 289