Javascript 使用 Node 在 JSON 数组中搜索项目(最好不要迭代)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11836050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:18:23  来源:igfitidea点击:

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

javascriptjsonnode.js

提问by Hymanie

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

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

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

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

回答by Bergi

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()methodon Arrays.

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

回答by shinzer0

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

由于节点实现的EcmaScript 5规范,可以使用阵列#过滤器obj.items

回答by mathisonian

edited to use native method

编辑为使用本机方法

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

回答by 3on

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

看看http://underscorejs.org这是一个很棒的库。

http://underscorejs.org/#filter

http://underscorejs.org/#filter

回答by Pablo Ezequiel

You could try find the expected result is using the find function, you can see the result in the following script:

您可以尝试使用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}

回答by Hymanie

Actually I found an even easier way if you are using mongoDB to persist you documents...

实际上,如果您使用 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)
      });
    }
  });
}

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.

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