以下是示例,请帮助使用等效的JavaScript代码
array A = [{id: 1, name:'cat'},{id:2, name:'dog'},{id:3, name:'tiger'}];
array B = [{name:'cat'},{name:'dog'}];
结果
expected = [{id: 1, name:'cat'},{id:2, name:'dog'}];
需要根据数组B中可用的名称过滤数组A
类似于('cat','dog')
中名称的SQL。
尝试使用array.filter
和indexOf !== -1
但没有得到预期的结果。
答案 0 :(得分:2)
随着阵列变大,构建查找对象可能会更好,但使用Array.prototype.filter()
和Array.prototype.some()
的简单方法可能如下所示:
const a = [{id: 1, name:'cat'}, {id:2, name:'dog'}, {id:3, name:'tiger'}];
const b = [{name:'cat'}, {name:'dog'}];
const result = a.filter(x => b.some(y => x.name === y.name));
console.log(result);

答案 1 :(得分:0)
const a = [{id: 1, name:'cat'}, {id:2, name:'dog'}, {id:3, name:'tiger'}];
const b = [{name:'cat'}, {name:'dog'}];
var res = a.filter((per)=>b.find((x)=>per.name===x.name))
console.log(res)