使用节点在 JSON 数组中搜索项目(最好不迭代)

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

本文关键字:迭代 项目 搜索 节点 JSON 数组      更新时间:2023-09-26

目前我得到这样的 JSON 响应...

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

我想执行这样的事情(伪代码)

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

然后这将返回

[{itemId:2,isRight:1}]

我知道我可以用 for 每个循环来做到这一点,但是,我试图避免这种情况。这目前是 Node.JS 应用程序的服务器端。

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

当然,你也可以编写一个函数来通过对象文字作为条件来查找项目:

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});

这两个函数都使用数组上的本机.filter()方法。

由于 Node 实现了 EcmaScript 5 规范,因此您可以在obj.items上使用 Array#filter 。

看看 http://underscorejs.org这是一个很棒的图书馆。

http://underscorejs.org/#filter

编辑为使用本机方法

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

你可以尝试使用find函数找到预期的结果,你可以在下面的脚本中看到结果:

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}

实际上,

如果您使用mongoDB来持久化文档,我发现了一种更简单的方法...

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)
      });
    }
  });
}

然后,您可以将 {isRight:1} 传递给该方法并仅返回对象的数组,从而允许我将繁重的工作推到有能力的 mongo 上。