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

后端 未结 6 913
孤城傲影
孤城傲影 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: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.

提交回复
热议问题