【问题标题】:How to filter/compare 2 arrays of objects by single property with lodash? [duplicate]如何使用 lodash 通过单个属性过滤/比较 2 个对象数组? [复制]
【发布时间】:2020-02-18 07:42:04
【问题描述】:

我有以下对象数组?

let arr1 = [{
  id: 1,
  props: []
}, {
  id: 2,
  props: []
}, {
  id: 3,
  props: []
}]

let arr2 = [{
  id: 1,
  props: ['a', 'b']
}, {
  id: 3,
  props: []
}]

我需要以某种方式比较这两个数组并返回一个新数组,该数组只包含 ID 不在两个原始数组中的对象。所以在上面的例子中,它应该只包含 ID 为 2 的对象,因为它只在 arr1 中。

我尝试使用

let arr3 = _.differenceWith(arr1, arr2, _.isEqual)

只要对象中的 props 数组相似并且我不更改它(我只在第二个数组中更改它),它就可以工作。

我也试过这个:

let arr3 = _.filter(arr1, o => o.id === _.find(arr2, obj2 => o.id === obj2.id))

但这根本不起作用。

有什么想法吗?

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    您可以使用_.differenceBy 和想要的密钥id 进行比较。

    let array1 = [{ id: 1, props: [] }, { id: 2, props: [] }, { id: 3, props: [] }],
        array2 = [{ id: 1, props: ['a', 'b'] }, { id: 3, props: [] }],
        difference = _.differenceBy(array1, array2, 'id');
    
    console.log(difference);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

    • 非常感谢!正要发布类似的答案! :)
    • 1 代表黄金 :)
    • @OriDrori,你真的查过了?
    • 不。最近刚看了top users
    【解决方案2】:

    使用reduceObject.values 会简化。

    let arr1 = [
      {
        id: 1,
        props: []
      },
      {
        id: 2,
        props: []
      },
      {
        id: 3,
        props: []
      }
    ];
    
    let arr2 = [
      {
        id: 1,
        props: ["a", "b"]
      },
      {
        id: 3,
        props: []
      }
    ];
    
    const updated = Object.values(
      [...arr1, ...arr2].reduce(
        (acc, curr) =>
          Object.assign(acc, { [curr.id]: curr.id in acc ? "" : { ...curr } }),
        {}
      )
    ).filter(x => x);
    
    console.log(updated);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2020-04-21
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多