Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用节点在JSON数组中搜索项(最好不进行迭代)_Javascript_Json_Node.js - Fatal编程技术网

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

Javascript 使用节点在JSON数组中搜索项(最好不进行迭代),javascript,json,node.js,Javascript,Json,Node.js,现在我得到了一个JSON响应,如下所示 {items:[ {itemId:1,isRight:0}, {itemId:2,isRight:1}, {itemId:3,isRight:0} ]} 我想执行类似这样的操作(伪代码) 这将返回 [{itemId:2,isRight:1}] 我知道我可以用for-each循环来实现这一点,但是,我正在努力避免这种情况。这是Node.JS应用程序的服务器端。请查看 这是一个很棒的图书馆 当然,您也可以编写一个函数,以通过对象文字作为条件来

现在我得到了一个JSON响应,如下所示

{items:[
  {itemId:1,isRight:0},
  {itemId:2,isRight:1},
  {itemId:3,isRight:0}
]}
我想执行类似这样的操作(伪代码)

这将返回

[{itemId:2,isRight:1}]
我知道我可以用for-each循环来实现这一点,但是,我正在努力避免这种情况。这是Node.JS应用程序的服务器端。

请查看 这是一个很棒的图书馆

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

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

这两个函数都使用on数组。

由于节点实现了EcmaScript 5规范,因此可以使用on
obj.items
编辑为使用本机方法

var arrayFound = obj.items.filter(function() { 
    return this.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

您可以尝试使用查找预期结果,您可以在以下脚本中看到结果:

var jsonItems={items:[
{itemId:1,isRight:0},
{itemId:2,isRight:1},
{itemId:3,isRight:0}
]}
var rta=jsonItems.items.find(
(it)=>{
返回它。isRight==1;
}
);
log(“RTA:+JSON.stringify(RTA));

//RTA:{“itemId”:2,“isRight”:1}
除非您有更多信息,否则迭代是不可避免的。但你为什么要排除它呢?你说的“没有迭代”是什么意思?这是怎么回事?我想我的意思是没有传统的过滤模式(每个循环都有一个规则),但我确信这是对regex和/或映射的创造性使用,也可以使用。他不太可能在Node.js中使用jQuery,即使可以使用,也应该使用本机过滤方法。是的,你是对的。我忘记了原生过滤方法。有趣的是,它仍然使用迭代。我不明白OP的意图。
var arrayFound = obj.items.filter(function() { 
    return this.isRight == 1; 
});
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)
      });
    }
  });
}