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

后端 未结 6 879
孤城傲影
孤城傲影 2020-12-16 03:06

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

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

I want

相关标签:
6条回答
  • 2020-12-16 03:22

    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.

    0 讨论(0)
  • 2020-12-16 03:26
    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.

    0 讨论(0)
  • 2020-12-16 03:35

    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}

    0 讨论(0)
  • 2020-12-16 03:36

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

    http://underscorejs.org/#filter

    0 讨论(0)
  • 2020-12-16 03:42

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

    0 讨论(0)
  • 2020-12-16 03:42

    edited to use native method

    var arrayFound = obj.items.filter(function() { 
        return this.isRight == 1; 
    });
    
    0 讨论(0)
提交回复
热议问题