【问题标题】:How to get intersection with lodash?如何与 lodash 相交?
【发布时间】:2019-05-03 18:19:22
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    洛达什

    可能最简洁的工作解决方案是使用 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)
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"&gt;&lt;/script&gt;

    使用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)
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"&gt;&lt;/script&gt;

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

    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)

    如果您在arr2 中有更多 id,您可以使用Array.filter

    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)

    【讨论】:

    • ... 或者只是 arr.find(x =&gt; arr2.includes("" + x.id)) 如果arr2 包含数字,则可以进一步简化:arr.find(x =&gt; arr2.includes(x.id))
    • 当然。好点子。不知道我有多想简化它,但既然你提到它,现在就想简化它:)
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多