简体   繁体   English

如何使用JavaScript在forEach循环中过滤结果

[英]How to filter results in forEach loop using javascript

I am having a hard time figuring out how to iterate over an array and only doing something when a specific value is found. 我很难弄清楚如何遍历数组,并且仅在找到特定值时才做某事。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

What I have in mind: 我的想法:

ForEach Entry, Where X = Y {
 console.log('I did something');
}

Actual Data: 实际数据:

[{
    "id" : 0,
    "fullName" : "George",
    "email": "george@test.ca",
    "group": 'Faculty',
    "totalFiles": 12,
    "outstandingFiles": 10,

},
{
    "id" : 1,
    "fullName" : "Albert",
    "email": "albert@test.ca",
    "group": 'Student',
    "totalFiles": 15,
    "outstandingFiles": 8,
}];

There are so many options to filter value without foreach, you can use find which will return the first matching value 不使用foreach筛选值的方法有很多,您可以使用find将返回第一个匹配值

 var myArray = [{ "id" : 0, "fullName" : "George", "email": "george@test.ca", "group": 'Faculty', "totalFiles": 12, "outstandingFiles": 10, }, { "id" : 1, "fullName" : "Albert", "email": "albert@test.ca", "group": 'Student', "totalFiles": 15, "outstandingFiles": 8, }]; var result = myArray.find(t=>t.group =='Faculty'); console.log(result); 

EDIT 编辑

 var myArray = [{ "id" : 0, "fullName" : "George", "email": "george@test.ca", "group": 'Faculty', "totalFiles": 12, "outstandingFiles": 10, }, { "id" : 1, "fullName" : "Albert", "email": "albert@test.ca", "group": 'Student', "totalFiles": 15, "outstandingFiles": 8, }]; myArray.filter(t=>t.group =='Faculty').forEach(result => console.log(result)); 

You can use filter if you want many results or find if you want the first result to your query 您可以使用过滤器 ,如果你想了许多成果或发现 ,如果你想第一个结果查询

This is an example using filter 这是使用过滤器的示例

const data = [
    {
        "id" : 0,
        "fullName" : "George",
        "email": "george@test.ca",
        "group": 'Faculty',
        "totalFiles": 12,
        "outstandingFiles": 10,
    },{
        "id" : 1,
        "fullName" : "Albert",
        "email": "albert@test.ca",
        "group": 'Student',
        "totalFiles": 15,
        "outstandingFiles": 8,
    }
];

const result = data.filter(info => {
    return info.group === 'Faculty'
})

console.log(result) will output console.log(result)将输出

[ { id: 0,
    fullName: 'George',
    email: 'george@test.ca',
    group: 'Faculty',
    totalFiles: 12,
    outstandingFiles: 10 } ]

You can learn about this and more array methods in http://javascript.info/array-methods 您可以在http://javascript.info/array-methods中了解此方法以及更多数组方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM