[英]javascript: filter objects by multiple values with array using a functional approach
I am trying to search a list of objects using a list of values and a list of keys.我正在尝试使用值列表和键列表来搜索对象列表。 My first approach is to create a list of objects given a particular value.
我的第一种方法是创建一个给定特定值的对象列表。 However, the key is hard-coded and I should be using a more functional approach.
但是,密钥是硬编码的,我应该使用更实用的方法。 Next, I think I should create a list of objects after filtering for each value.
接下来,我想我应该在过滤每个值后创建一个对象列表。 However, I am again hard-coding the values.
但是,我再次对这些值进行了硬编码。 I am not sure how to pass a list of values and a list of keys such as the following.
我不确定如何传递值列表和键列表,如下所示。 Should I have used a Map object?
我应该使用 Map 对象吗? if so, how can I extract the following two variables?:
如果是这样,我如何提取以下两个变量?:
const list_of_keys = ['color_1', 'color_2', 'color_3']
const list_of_values = ['red','blue','purple']`
const data = [
{make: 'ford',model: 'mustang',color_1: 'red',color_2: '',color_3: ''},
{make: 'ford',model: 'escape',color_1: '',color_2: 'blue',color_3: ''},
{make: 'ford',model: 'expedition',color_1: '',color_2: '',color_3: 'purple'},
{make: 'mercedez',model: 'helicopter',color_1: '',color_2: '',color_3: 'orange'}
]
// hard-coded object keys
const filter_by_multiple_keys = (carObject, Value) => carObject.filter(car =>
car.color_1 === Value ||
car.color_2 === Value ||
car.color_3 === Value
);
// hard-coded values
const filterByColorsObject = list_of_objects => {
const dataArray = [];
dataArray.push(filter_by_multiple_keys(list_of_objects, 'red'));
dataArray.push(filter_by_multiple_keys(list_of_objects, 'blue'));
dataArray.push(filter_by_multiple_keys(list_of_objects, 'purple'));
return(dataArray)
}
console.log(filterByColorsObject(data))
Creating an array of the key names is the right idea - check if .some
of them, when that property is accessed on the object, are equal to the value:创建一个键名数组是正确的想法 - 检查
.some
的一些,当在对象上访问该属性时,是否等于值:
const filter_by_multiple_Columns = (carObject, value) => carObject.filter(
car => list_of_keys.some(
key => car[key] === value
)
);
To construct multiple columns, .map
from the list_of_values
array:要构造多列,请使用
list_of_values
数组中的.map
:
const filterByColorsObject = list_of_objects => list_of_values.map(
value => filter_by_multiple_Columns(list_of_objects, value)
);
But this is an extremely strange data structure.但这是一种极其奇怪的数据结构。 If at all possible, change the
colors
properties to an array , instead of multiple separate properties:如果可能,请将
colors
属性更改为数组,而不是多个单独的属性:
{ make: 'mercedez',model: 'helicopter', colors: ['', '', 'orange'] }
or或者
{ make: 'mercedez',model: 'helicopter',colors: ['orange'] }
This would make them much easier to iterate over.这将使它们更容易迭代。 For the above, you would do:
对于上述情况,您将执行以下操作:
const filter_by_multiple_Columns = (carObject, Value) => carObject.filter(
car => car.colors.includes(Value)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.