简体   繁体   English

如何连接具有不同结构的两个数组

[英]How to Join two Arrays with different structures

using typescript, I have two arrays (different structure) I am looking to get all the apps from array1 which they don't exist in array 2( array 2 has one more layer apps) join is based on app_id使用打字稿,我有两个数组(不同的结构)我希望从数组 1 中获取它们在数组 2 中不存在的所有应用程序(数组 2 还有一层应用程序)加入基于 app_id

Array 1数组 1

[
  {
    "app_id": 2,
    "app_type_id": 1,
    "app_name": "Test 5",

  },
  {
    "app_id": 26,
    "app_type_id": 3,
    "app_name": "Test 4",
  },
  {
    "app_id": 177,
    "app_type_id": 2,
    "app_name": "Test 1",
  },
  {
    "app_id": 209,
    "app_type_id": 1,
    "app_name": "Test 2",
  }
]

Array 2阵列 2

[
  {
    "app_type_id": 2,
    "apps": [
      {
        "app_id": 177,
        "app_type_id": 2,
        "app_name": "Test 1",
      }
    ]
  },
  {
    "app_type_id": 1,
    "apps": [
      {
        "app_id": 209,
        "app_type_id": 1,
        "app_name": "Test 2",
      },
      {
        "app_id": 191,
        "app_type_id": 1,
        "app_name": "Test 3",
      }
    ]
  }
]

Expected Output Array 3预期输出数组 3

[
  {
    "app_id": 2,
    "app_type_id": 1,
    "app_name": "Test 5",

  },
  {
    "app_id": 26,
    "app_type_id": 3,
    "app_name": "Test 4",
  }
]

TS File Tried this but it dd not work, it is returning all records TS 文件试过这个,但它不工作,它正在返回所有记录

this.array3= this.array1.filter(o1 => this.array2.filter(o2 => o2.apps.filter(u => u.app_id === o1.app_id).length===0)); 

you can try你可以试试

array1.filter(e1 =>
  !array2.some(e2 => e2.apps.some(v => v[`app_id`] === e1[`app_id`]))
)

you might also want to handle null/undefined if that is the case.如果是这种情况,您可能还想处理 null/undefined。

You can use this code, I break it down in multiple sentences to be more clear what is going on您可以使用此代码,我将其分解为多个句子以更清楚发生了什么

const appIds = this.array2.map(i => (i.apps || []).map(item => item.app_id))
const allAppIds : any = appIds.reduce((a, b) => { return a.concat(b); },[]);

const notExistsItems = this.array1.filter(item => !allAppIds.includes(item.app_id));

see this working result https://stackblitz.com/edit/angular-stackoverflow-54407756看到这个工作结果https://stackblitz.com/edit/angular-stackoverflow-54407756

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM