这是我的数据
[{name:'james',grade:'A'},
{name:'john',grade:'B'},
{name:'iris',,grade:'A'},
{name:'ivan',,grade:'C'}]
我想保留具有A级和C级的对象,它很容易我可以像
一样进行过滤 person.filter(obj => obj.grade === 'A' || obj.grade === 'C')
但现在我有一个对象数组。
[{grade:'A'},{grade:'C'}]
任何线索如何立即进行过滤?我需要嵌套循环吗?
答案 0 :(得分:1)
let person = [{name:'james', grade:'A'},
{name:'john', grade:'B'},
{name:'iris', grade:'A'},
{name:'ivan', grade:'C'}];
let predicate = [{grade:'A'},{grade:'C'}];
let result = person.filter(obj => predicate.some(p => p.grade == obj.grade))
console.log('result:', result)

如果您的谓词比这更具动态,请比较所有对象属性,而不仅仅是p.grade
。
person.filter(obj => predicate.some(p => {
return Object.keys(p).every(k => obj[k] == p[k]);
}));
答案 1 :(得分:0)
使用下划线库 例如 -
var bbb = [
{id: 839},
{id: 854}
];
var ids = {};
_.each(bbb, function (bb) { ids[bb.id] = true; });
var data = [{grade:'A'},{grade:'C'}];
var value = {};
_.each(data , function (d) { value[data.garde] === 'A' | value[data.garde] === 'C' ; });
答案 2 :(得分:0)
成绩为select AnyCommunicationProblem, count(*) cnt
from PROTOS_PersonalInformation
GROUP BY AnyCommunicationProblem
和A
的对象应该被过滤为(经典的js语法),
C
答案 3 :(得分:0)
如果你有很多成绩要检查(我不知道所有的成绩;))。您可以先将数组转换为Set
const grades = new Set([{grade:'A'},{grade:'C'}].map(({grade}) => grade))
const persons = [{name:'james',grade:'A'},
{name:'john',grade:'B'},
{name:'iris',grade:'A'},
{name:'ivan',grade:'C'}]
然后使用has
const filtered = persons.filter(({grade}) => grades.has(grade))
答案 4 :(得分:0)
您可以使用Set
作为谓词并相应地过滤
let person = [{ name: 'james', grade: 'A' }, { name: 'john', grade: 'B' }, { name: 'iris', grade: 'A' }, { name: 'ivan', grade: 'C' }],
predicate = [{ grade: 'A' }, { grade: 'C' }],
result = person.filter((s => p => s.has(p.grade))(new Set(predicate.map(p => p.grade))));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }