代码之家  ›  专栏  ›  技术社区  ›  bier hier

如何与lodash相交?

  •  4
  • bier hier  · 技术社区  · 7 年前

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

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

    1 回复  |  直到 7 年前
        1
  •  29
  •   Akrion    7 年前

    洛达斯

    可能最简洁的工作解决方案是使用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)
    <脚本src=”https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js“></脚本>

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

    ES6&纯Javascript

    您只能通过以下方式使用JS执行此操作: Array.find

    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 在这种情况下,你有更多的身份证 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.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)