本文介绍了根据另一个对象数组中的过滤条件来过滤对象数组:JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望根据 myFilter
中提到的条件过滤 myArray
。
myFilter的键已定义,可以使用 myFilter.field
, myFilter.value
进行访问。键: myArray
的值未知。
我们可能必须遍历 myArray
中的每个对象,才能首先将myArray [key]与 myFilter.field $ c $匹配c>然后将myArray [key]指向myFilter.value。
I wish to filter myArray
based on criteria mentioned in myFilter
.The keys of myFilter are defined and could be accessed using myFilter.field
, myFilter.value
where as key:value of myArray
are unknown.We might have to iterate over each object in myArray
to first match the myArray [key] with myFilter.field
and then to that myArray [key] to myFilter.value.
这应该是AND逻辑
myArray = [{
make: "Honda",
model: "CRV",
year: "2017"
},
{
make: "Toyota",
model: "Camry",
year: "2020"
},
{
make: "Chevy",
model: "Camaro",
year: "2020"
}
]
myFilter = [{
field: "make",
value: "Chevy",
type: "string"
},
{
field: "year",
value: "2020",
type: "date"
}
];
// Expected OutPut:
myArray = [{
make: "Chevy",
model: "Camaro",
year: "2020"
}]
var tempArray = [];
const keysToMatch = myFilter.length;
let matchedItems = [];
myArray.forEach((data) => {
matchedItems = [];
let itemsToFind = Object.values(data);
myFilter.forEach((filterItem) => {
if (itemsToFind.indexOf(filterItem.value) != -1) {
matchedItems.push("matched");
}
});
//check if everything matched
if (matchedItems.length === keysToMatch) {
tempArray.push(data);
}
});
console.log(tempArray);
推荐答案
根据您的需要,这可能有些复杂,但是可以。
This might be a bit over complicated for what you need, but it works.
myArray = [
{
make: "Honda",
model: "CRV",
year: "2017"
},
{
make: "Toyota",
model: "Camry",
year: "2020"},
{
make: "Chevy",
model: "Camaro",
year: "2020"}
]
myFilter = [
{
field: "make",
value: "Chevy",
type: "string"
},
{
field: "year",
value: "2020",
type: "date"
}
];
//only return those that return true
var newArray = myArray.filter(car => {
var temp = true;
//iterate over your filters
for (var i = 0; i < myFilter.length; i++) {
//if any filters result in false, then temp will be false
if (car[myFilter[i].field] != myFilter[i].value) {
temp = false;
}
}
if (temp == true) {
return true;
} else {
return false;
}
});
console.log(JSON.stringify(newArray));
这篇关于根据另一个对象数组中的过滤条件来过滤对象数组:JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!