1 回答
TA贡献1811条经验 获得超4个赞
您可以迭代数据数组,然后检查所有需要的工具是否都在实际对象中。
let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],
required = ['Jaw', 'Taw'],
result = array.filter(({ tools }) =>
required.every(v => tools.some(({ toolname }) => toolname === v))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
另一种通过使用 Set 多次省略循环的方法。tools
let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],
required = ['Jaw', 'Taw'],
result = array.filter(({ tools }) =>
required.every(
Set.prototype.has,
new Set(tools.map(({ toolname }) => toolname))
)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报