繁体   English   中英

基于另一个数组的过滤器打字稿数组

[英]filter typescript array based on another array

有几个基于简单数组的示例,但是我有2个对象数组,似乎无法使它正常工作。

getAvailableApplications() : Application[]
  {
  var list;
  if (!this.userSettings)
    list = this.applications;
  else
    list =  
      this.applications.filter(x=>
      this.userSettings.modules.filter(y=>
       x.entityId === y.moduleId
     ));

return list;    
}

尽管我在userSettings.modules数组中有一个元素,但这总是返回给我完整的应用程序列表,而不是删除不在userSetting.modules数组中的应用程序。

我也尝试了不带lambda的重写,但似乎无法识别模块级别的userSettings变量

      this.applications.filter(function (x){
    return this.userSettings.filter(function(y){
        return x.entityId === y.moduleId;
    })

userSettings被声明为any,但是分配了一个类似

  userSettings = {"settings":{"modules":[{"moduleId":"b37f590de59943278e7f9b2137c0c232",
  "order":0}]}

应用程序的声明如下:

 applications : Application[]

如果我正确理解,这就是您要实现的目标,无需使用两个过滤器。

list = this.applications
  .filter(x => this.userSettings.modules.map(y => y.moduleId).includes(x.entityId));

参见示例:

 const first = [{entityId: 1}, {entityId: 2}, {entityId: 3}]; const second = [{moduleId: 1}, {moduleId: 3}]; const list = first.filter(x => second.map(y => y.moduleId).includes(x.entityId)); console.log(list); 

您要完成的任务如下:

this.applications.filter( x => 
    this.userSettings.some(y => 
        x.entityId === y.moduleId;
    )
)

“ some()方法测试数组中的至少一个元素是否通过了由提供的函数实现的测试。”

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

暂无
暂无

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

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