是否有一个方法来过滤单一属性的数组?


const buttons = [
{ id: 1, text: 'First' },
{ id: 2, text: 'Second' },
{ id: 3, text: 'Third' }
]
const activeButtonIds = [1, 3]
使用<<p> strong> lodash ,我想过滤掉id不包含在activeButtonIds = [1, 3]中的所有按钮。

最明显的方法是:

_.filter(buttons, ({ id }) => _.includes(activeButtonIds, id))

但我在想,有没有一种更简单的方法来实现同样的事情?lodash中的内置函数

?

您可以使用_.intersectionWith()查找包含在两个数组中的项目,使用运算符函数:

const buttons = [{"id":1,"text":"First"},{"id":2,"text":"Second"},{"id":3,"text":"Third"}]
const activeButtonIds = [1, 3]
const result = _.intersectionWith(buttons, activeButtonIds, (button, activeId) =>
button.id === activeId
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>