根据嵌套数组中的某些值找出两个数组之间的差异

Find the difference between two arrays based on some the value inside a nested array

我有两个数组

arrayOfItems: [
    {
    id: '4321-3321-4423', 
    value: 'some text'
    },

    {
    id: '4322-4654-9875', 
    value: 'some text again'
    }
]

然后是第二个数组

itemX: [
    {
    id: '3214-6543-4321', 
    nestedArrayOfItems:[
        {id: '4321-3321-4423'}
        {id: '3455-8765-7764'}
    ]
    }
]

我需要创建一个基于 arrayOfItems 的新数组,该数组不包含 itemX.nestedArrayOfItems

中的任何 ID

因为它是一个嵌套的数组,所以我在我需要做的事情上画了一个空白...我正在搜索 Lodash 看看是否有一些东西不涉及我使用一堆 for循环。

这个怎么样:

let difference = arrayOfItems.filter(x => ! itemX.nestedArrayOfItems.includes(x));

PS : ID 必须是字符串

您可以使用 Array.prototype.filter() 然后检查 id 是否存在 Array.prototype.some() 像这样:

const arrayOfItems = [
  {
  id: '4321-3321-4423', 
  value: 'some text'
  },

  {
  id: '4322-4654-9875', 
  value: 'some text again'
  }
]

const itemX = [
  {
  id: '3214-6543-4321', 
  nestedArrayOfItems: [
      {id: '4321-3321-4423'},
      {id: '3455-8765-7764'}
  ]
  }
]

const res = arrayOfItems.filter(item => !itemX[0].nestedArrayOfItems.some(({ id }) => id === item.id))

console.log(res);