我有一个对象数组,如下所示:
0: {Id: 1, name: 'xyz', pqID: 10, pqType: null}
1: {Id: 2, name: 'abc', pqID: 15, pqType: null}
2: {Id: 3, name: 'wer', pqID: 16, pqType: null}
3: {Id: 4, name: 'uyt', pqID: 18, pqType: null}
4: {Id: 5, name: 'qwe', pqID: 22, pqType: null}
5: {Id: 6, name: 'ert', pqID: 25, pqType: null}
我想要pqID
, 10和15的对象。下面是我正在尝试的,它给出了空数组:
const newUsers = arr.filter(
(user) => user.pqID == 10 && user.pqID == 15
);
console.log(newUsers);
你可以试试,用完整的数组函数语法:
const newUsers = arr.filter(
(user) => {return [10, 15].includes(user.pqID)}
);
或者不带括号和花括号的简化版本:
const newUsers = arr.filter(user => [10, 15].includes(user.pqID));
注意||
操作符
var arr =
[{Id: 1, name: 'xyz', pqID: 10, pqType: null},
{Id: 2, name: 'abc', pqID: 15, pqType: null},
{Id: 3, name: 'wer', pqID: 16, pqType: null},
{Id: 4, name: 'uyt', pqID: 18, pqType: null},
{Id: 5, name: 'qwe', pqID: 22, pqType: null},
{Id: 6, name: 'ert', pqID: 25, pqType: null}]
const newUsers = arr.filter(
(user) =>
user.pqID == 10 || user.pqID == 15 // note ||
);
console.log(newUsers)