I want to simplify an array of objects. Let's assume that I have following array:
var users = [{ name: 'John', email: '[email protected]', age: 25, address: 'USA' }, { name: 'Tom', email: '[email protected]', age: 35, address: 'England' }, { name: 'Mark', email: '[email protected]', 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 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 first iteration when prop - address
will be equal 'England'
two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name
will be equal Mark
only the last user should be added to array result, but i end up with two elements in array.
I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.
To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
You can do like this
var filter = { address: 'England', name: 'Mark' }; var users = [{ name: 'John', email: '[email protected]', age: 25, address: 'USA' }, { name: 'Tom', email: '[email protected]', age: 35, address: 'England' }, { name: 'Mark', email: '[email protected]', age: 28, address: 'England' } ]; users= users.filter(function(item) { for (var key in filter) { if (item[key] === undefined || item[key] != filter[key]) return false; } return true; }); console.log(users)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With