代码之家  ›  专栏  ›  技术社区  ›  Sergino

基于另一个数组向Observable数组添加附加属性

  •  0
  • Sergino  · 技术社区  · 7 年前

    我有两个可观测的数组类型 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);

    有什么解决办法吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Chris Tapay    7 年前

    请注意 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
  •  2
  •   Bradley Taniguchi    7 年前

    在您的代码片段中,您有一个输入错误,在这里,您将组合的最新RXJS运算符的结果设置为 combined$ ,然后你称之为 combined 下一行,我认为是不正确的,或者在将此问题转换为so时只是一个翻译错误。(不管怎样,必须指出他)

    下一步, 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 .

        3
  •  2
  •   Dhananjai Pai    7 年前

    我认为组合发送一个值,它是一个单独值的数组。在这里 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 )
        });
      })
    );