Jac*_*kie 10 javascript json node.js
目前我收到这样的JSON响应......
{items:[
{itemId:1,isRight:0},
{itemId:2,isRight:1},
{itemId:3,isRight:0}
]}
Run Code Online (Sandbox Code Playgroud)
我想执行这样的事情(伪代码)
var arrayFound = obj.items.Find({isRight:1})
Run Code Online (Sandbox Code Playgroud)
然后这将返回
[{itemId:2,isRight:1}]
Run Code Online (Sandbox Code Playgroud)
我知道我可以为每个循环执行此操作,但是,我试图避免这种情况.这是Node.JS应用程序上的服务器端.
Ber*_*rgi 23
var arrayFound = obj.items.filter(function(item) {
return item.isRight == 1;
});
Run Code Online (Sandbox Code Playgroud)
当然,您也可以编写一个函数来按对象文字查找项目作为条件:
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});
Run Code Online (Sandbox Code Playgroud)
这两个函数都在Arrays上使用本机.filter()方法.
| 归档时间: |
|
| 查看次数: |
40801 次 |
| 最近记录: |