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
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
[ { 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.