[英]filter array of objects based on separate object keys, values
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.新数组应该是空的,因为数组中没有人具有 32 和 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.
请记住,过滤器的键和值会一直动态变化。
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);
You can use the function filter
and the function every
to check that every key-value are equal to the FILTERS
values.您可以使用函数
filter
和函数every
来检查每个键值是否等于FILTERS
值。
Assuming when within the FILTERS a value is empty then skip it假设在 FILTERS 中的值是空的,然后跳过它
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: '' };
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.