簡體   English   中英

獲取嵌套對象數組中的鍵值(RxJS Observable)

[英]Get value of key in nested array of objects (RxJS 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值。 在這種情況下,重要的是不要 select 只是data的第二個數組元素,因為順序可能會有所不同。 我能做些什么?

 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) );

您可以將 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);

所以 stream 看起來像

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

如果您不知道屬性是否始終可用(這可能會導致undefined的錯誤),您可以使用可選的鏈接運算符?. .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM