I want to simplify an array of objects. Let's assume that I have the following array:
var users = [{
name: 'John',
email: 'johnson@mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom@mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark@mail.com',
age: 28,
address: 'England'
}];
And filter object:
var filter = {address: 'England', name: 'Mark'};
For example, i need to filter all users by address and name, so i do a loop through filter object properties and check it out:
function filterUsers (users, filter) {
var result = [];
for (var prop in filter) {
if (filter.hasOwnProperty(prop)) {
//at the first iteration prop will be address
for (var i = 0; i < filter.length; i++) {
if (users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
}
return result;
}
So, during the first iteration, when prop - address equals 'England,' two users (named Tom and Mark) are added to the array result, but during the second iteration, when prop name equals Mark, only the last user should be added to the array result, but I end up with two items in the array.
I have a rough notion of why this is happening, but I'm stuck and can't figure out how to solve it.
Any assistance is much appreciated.
Thanks.