如何与lodash相交?

时间:2018-12-02 03:27:25

标签: javascript lodash

我正在尝试在此对象数组中返回匹配的ID:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

如何仅返回arr中值为1的id?

1 个答案:

答案 0 :(得分:10)

Lodash

最简洁的解决方案可能是使用lodash _.intersectionBy,但这需要您的arr2数组包含一个带有id的对象:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =[{id:1}]  // <-- object with the `id`

const result = _.intersectionBy(arr, arr2, 'id');

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

使用lodash执行此操作的另一种方法是通过_.intersectionWith,它不需要对给定的输入进行任何更改:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = _.intersectionWith(arr, arr2, (o,num) => o.id == num);

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

这个想法是为它提供一个自定义函数,以了解如何比较两个数组之间的值。

ES6和纯Javascript

如果您只想查找一项,则只能通过Array.find使用JS进行此操作:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr.find(x => arr2.some(y => x.id == y))
console.log(result)

如果Array.filter中有更多ID,则可以使用arr2

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1", "2"]

const result = arr.filter(x => arr2.some(y => x.id == y))
console.log(result)

由于您在arr中有ID,因此您也可以只使用Array.map

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr2.map(x => arr.find(y => y.id == x))
console.log(result)

@ibrahim mahrir提到的另一种选择是通过Array.findArray.includes

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

const result = arr.filter(x => arr2.includes(x.id.toString()))
console.log(result)