如何在两个对象数组上执行javascript“ except”?
我有这个数组:
arr = [
{state: "FL"},
{state: "NY"},
{gender: "Male"},
{gender: "Female"},
{year: "1990"}
]
我有一个包含需要排除的itens的数组:
excludeArr = [
{state: "FL"},
{gender: "Male"},
]
所需的数组是这样:
finalArr = [
{state: "NY"},
{gender: "Female"},
{year: "1990"}
]
我尝试过,但是它返回了所有元素:
var arr = [
{state: "FL"},
{state: "NY"},
{gender: "Male"},
{gender: "Female"},
{year: "1990"}
]
var excludeArr = [
{state: "FL"},
{gender: "Male"},
]
var finalArr = arr.filter(function (o1) {
const [key, val] = Object.entries(o1)[0];
return excludeArr.filter(element => {
if(element[key] !== val) {
return element
}
});
});
console.log(finalArr)
答案 0 :(得分:3)
您可以使用Array.filter()
方法:
finalArr = arr.filter(function(obj){
return !excludeArr.map(x => JSON.stringify(x)).includes(JSON.stringify(obj));
});
或者作为单线:
finalArr = arr.filter(obj => !excludeArr.map(x => JSON.stringify(x)).includes(JSON.stringify(obj)));
答案 1 :(得分:1)
您的代码无法正常工作,因为您在内部循环中使用过滤器,并且在内部循环中使用element[key] !== val
,好像条件总是会导致返回一些值,而这些值又会按所提供的变为真输入。
您可以将代码更改为类似的内容。在这里,我正在使用some检查arr
内excludeArr
中值是否不存在
var arr = [{state: "FL"},{state: "NY"},{gender: "Male"},{gender: "Female"},{year: "1990"}]
var excludeArr = [{state: "FL"},{gender: "Male"},]
var finalArr = arr.filter(ele => !excludeArr.some(inner => Object.values(ele)[0] === Object.values(inner)[0]))
console.log(finalArr)
答案 2 :(得分:1)
您快到了。您不想过滤exclude数组,而是要检查其中的任何元素是否具有与要检查的元素相同的键和值。
var arr = [
{state: "FL"},
{state: "NY"},
{gender: "Male"},
{gender: "Female"},
{year: "1990"}
]
var excludeArr = [
{state: "FL"},
{gender: "Male"},
]
var finalArr = arr.filter(function (o1) {
const [key, val] = Object.entries(o1)[0];
return !excludeArr.some( element => element[key] === val );
});
console.log(finalArr)