问题
I have the array of people below:
const FIRST_ARRAY = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
I would like to filter the array to produce a separate array based on a 'filters' object.
For example if my filters are:
const FILTERS = {
age: 32,
name: 'John',
occupation: ''
};
The new array should be empty as no people in the array have the combination of 32 and John. However if my filters are:
const FILTERS = {
age: 32,
name: 'Simon',
occupation: ''
}
The new array of people returned will be:
const NEW_ARRAY = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
}
];
How can I filter the array of people by iterating over the 'filters' object values? Bare in mind the filters keys and values will dynamically changing all the time.
回答1:
You could filter as follows:
const FIRST_ARRAY = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
const FILTERS = {
name: 'Simon',
age: 32,
occupation: ''
};
const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS)
.every(([key, val]) => val !== '' ? person[key] === val : true));
console.log(filtered);
回答2:
You can use the function filter
and the function every
to check that every key-value are equal to the FILTERS
values.
Assuming when within the FILTERS a value is empty then skip it
const FIRST_ARRAY = [{name: 'Simon',age: 32,occupation: 'Student'},{name: 'Vera',age: 22,occupation: 'Developer'}],
FILTERS = {age: 32,name: 'Simon',occupation: ''},
keys = Object.keys(FILTERS),
result = FIRST_ARRAY.filter(o => keys.every(k => FILTERS[k] === '' || FILTERS[k] === o[k]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const FILTERS = { age: 32, name: 'John', occupation: '' };
回答3:
You can try something like:
function compare(item, filter) {
for (var property in filter) {
if (filter.hasOwnProperty(property)) {
let value = filter[property];
return item.hasOwnProperty(property) && item[property] != '' && value == item[property];
}
}
}
const DATA = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
const filter = {
age: 32,
name: 'Simon',
occupation: ''
};
let result = DATA.filter(function(item) {
return compare(item, filter);
})
console.log(result);
来源:https://stackoverflow.com/questions/54936172/filter-array-of-objects-based-on-separate-object-keys-values