【问题标题】:Get value of key in nested array of objects (RxJS Observable)获取嵌套对象数组中的键值(RxJS Observable)
【发布时间】:2022-01-15 02:34:23
【问题描述】:

通过我的 observable testData$ 我收到如下数据:

      [
        {
          type: 'userInfo',
          data: [
            {
              username: 'Sara',
              age: 27,
            },
            {
              username: 'Max',
              age: 31,
            },
            {
              username: 'Kim',
              age: 26,
            },
          ],
        },
        {
          type: 'cars',
          data: [
            {
              type: 'Mercedes'
            },
          ],
        },    
      ];

来自testData$ 我想获取Max 的年龄并将其存储在maxAge$ 中。到目前为止,我已经尝试过这段代码:

  public maxAge$ = this.testData$.pipe(
    map(x => x.filter(obj => obj.type === 'userInfo')),
    map(value => value[0]),
    pluck('data'),
  );

它像这样返回数据数组:

[
  {
    username: 'Sara',
    age: 27,
  },
  {
    username: 'Max',
    age: 31,
  },
  {
    username: 'Kim',
    age: 26,
  },
]

但现在我不知道如何从这里继续获取 Max 的age-value。在这种情况下,重要的是不要只选择 data 的第二个数组元素,因为顺序可能会有所不同。我能做什么?

【问题讨论】:

    标签: javascript arrays angular object rxjs


    【解决方案1】:

    const users = [
      {
        username: 'Sara',
        age: 27,
      },
      {
        username: 'Max',
        age: 31,
      },
      {
        username: 'Kim',
        age: 26,
      },
    ]
    cons maxage = users.find(user=>user.username=='MAX').age;
    
    
     public maxAge$ = this.testData$.pipe(
        map(x => x.find(obj => obj.type === 'userInfo').data),
        map(users => users.find(user=>user.username==='Max').age)
      );

    【讨论】:

      【解决方案2】:

      您可以将 RxJS map 运算符与 Array#find 方法一起使用

      const testData = [{ type: 'userInfo', data: [{ username: 'Sara', age: 27, }, { username: 'Max', age: 31, }, { username: 'Kim', age: 26, }, ], }, { type: 'cars', data: [{ type: 'Mercedes' }, ], }, ];
      
      const maxAge = testData
        .find(item => item.type === 'userInfo')
        .data
        .find(item => item.username === 'Max')
        .age;
        
      console.log(maxAge);

      所以流看起来像

      public maxAge$ = this.testData$.pipe(
        map((testData: any) => testData
          .find(item => item.type === 'userInfo')
          .data
          .find(item => item.username === 'Max')
          .age
        )
      );
      

      如果您不知道这些属性是否始终可用(这可能导致undefined 错误),您可以使用optional chaining operator ?.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2021-11-30
        • 2020-02-08
        • 1970-01-01
        • 2021-09-01
        • 2013-12-31
        • 2021-11-29
        相关资源
        最近更新 更多