如何与lodash相交? [英] How to get intersection with lodash?
问题描述
我正在尝试在此对象数组中返回匹配的ID:
I am trying to return the matching ids in this array of objects:
const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]
如何仅返回arr中值为1的id?
How can I return just the id with value 1 in arr?
推荐答案
Lodash
最简洁的解决方案可能是使用lodash的 _.intersectionBy
,但这将要求您的 arr2
数组包含一个具有 id 的对象代码>:
Probably the most concise working solution would be using the lodash _.intersectionBy
but that would require your arr2
array to contain an object with an 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
,不需要对给定的输入进行任何更改:
Another way to do this with lodash
would be via _.intersectionWith
which does not require any changes on your given inputs:
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>
这个想法是为它提供一个自定义函数,以了解如何比较两个数组之间的值.
The idea would be to provide it with a custom function to know how to compare the values between the 2 arrays.
ES6&纯Javascript
如果您只想查找一项,则只能通过 Array.find
使用JS进行此操作:
You can do this with JS only via Array.find
if you are looking for just one item:
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)
如果在 arr2
中有更多ID,则可以使用 Array.filter
:
You can use Array.filter
in the case you have more ids in 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
:
Since you have the ids in the arr you could also just use 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.find
& Array.includes
:
Another option as mentioned by @ibrahim mahrir
would be via Array.find
& Array.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)
这篇关于如何与lodash相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!