附加属性添加到基于另一个阵列可观测阵

问题描述 投票:0回答:3

我有两个可观察阵列类型Observable<MyType>

export interface MyType{
  title: string;
  id: string;
  other: [];
}

我想附加属性exists添加到第一阵列并将其设置为true如果产品存在第二阵列中:

  const combined$ = combineLatest(this.first$, this.second$);
    this.output$ = combined.pipe(
      map((x, y) => {
        return x.map(a => {
          a.title = a.title;
          a.id = a.id;
          a.other = a.other;
          a.exists = y.find(b => b.id === a.id )
        });
      })
    );

始终让[...undefined]结果,如果订阅了output观察到this.output$.subscribe(console.log);

任何想法如何解决?

angular rxjs angular2-observables
3个回答
2
投票

请注意,find返回数组(否则未定义)中发现的元素。更好地利用some。另外,当你在地图上返回的对象,你应该使用一个普通的return陈述或括号中的对象。

const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined.pipe(
    map(([x, y]) => {
        return x.map(a => {
            return { 
                ...a,
                exists: y.some(b => b.id === a.id)
            };
         });
     })
);

2
投票

在您的代码段你有,你从combinedLatest rxjs运营商为combined$,那么过渡这个问题,所以当把它作为combined下一行,我认为是不正确,或只是一个翻译错误结果设置一个错字。 (不管,必须指出来嘿嘿)

接着,操作者combineLatest返回所有观测值的数组。因此,你可以用解构的map操作中很容易地从所有观测的最新值。

下面是最后的代码:

const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined.pipe(
  map(([x, y]) => {
    return x.map(a => {
      a.title = a.title;
      a.id = a.id;
      a.other = a.other;
      a.exists = y.find(b => b.id === a.id )
    });
  })
);

在原始代码中,你基本上传递值作为x的阵列。


2
投票

我认为组合发送一个值,它是单独的值的阵列。这里y将是不确定的。

使用([X,Y])来解构里面映射中的值,然后再试一次。合并$也有你错过了一个错字。而find可以some代替,以更好地代表逻辑,并返回一个布尔

此外,当您使用x.map你在逻辑映射错阵列。

const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined$.pipe(
  map(([x, y]) => {
    return x.map(a => {
      a.title = a.title;
      a.id = a.id;
      a.other = a.other;
      a.exists = y.some(b => b.id === a.id )
    });
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.