使用节点搜索JSON数组中的项目(最好不进行迭代) [英] Searching for items in a JSON array Using Node (preferably without iteration)

查看:99
本文介绍了使用节点搜索JSON数组中的项目(最好不进行迭代)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我收到这样的JSON回复......

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

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

这会然后返回

[{itemId:2,isRight:1}]

我知道我可以为每个循环执行此操作,但是,我试图避免这种情况。这是Node.JS应用程序的当前服务器端。

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.

推荐答案

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

两个函数都使用 native .filter()方法

Both functions make use of the native .filter() method on Arrays.

这篇关于使用节点搜索JSON数组中的项目(最好不进行迭代)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆