过滤器数组的属性和值的另一个数组- Javascript



我有两个数组

const condition = [
{ iosSend: true },
{ androidSend: true }
]

const myArray = [
{
androidSend: false,
iosSend: true,
macosSend: false,
id: 1
},
{
androidSend: true,
iosSend: false,
macosSend: false,
id: 2
},
{
androidSend: true,
iosSend: true,
macosSend: false,
id: 3
},
{
androidSend: false,
iosSend: false,
macosSend: true,
id: 4
}
]

我想用以下条件过滤myArray:返回一个数组,其中的对象至少具有条件array = false中object的一个键。

我的意思是,在这个例子中,返回应该返回一个数组对象id为1、2和4

哪一个是最好的方法?

如果您想要匹配任何条件的所有项,下面是一个过滤的示例。

const condition = {
iosSend: false,
androidSend: false
};

const myArray = [
{
androidSend: false,
iosSend: true,
macosSend: false,
id: 1
},
{
androidSend: true,
iosSend: false,
macosSend: false,
id: 2
},
{
androidSend: true,
iosSend: true,
macosSend: false,
id: 3
},
{
androidSend: false,
iosSend: false,
macosSend: true,
id: 4
}
];
const conditions = Object.entries(condition);
const filteredArr = myArray.filter(o => {
for (const [key, val] of conditions) {
if (key in o && o[key] == val) return true;
}
return false;
});
console.log(filteredArr);

#编辑:在澄清了作者

的评论后,我将条件更改为iosSend false或androidSend false。

最新更新