简体   繁体   English

获取嵌套对象数组中的键值(RxJS Observable)

[英]Get value of key in nested array of objects (RxJS Observable)

Through my observable testData$ I receive data that looks like this:通过我可观察的testData$ ,我收到如下所示的数据:

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

From testData$ I want to get the age of Max and store it in maxAge$ .testData$我想获取 Max 的年龄并将其存储在maxAge$中。 I have tried this code so far:到目前为止,我已经尝试过这段代码:

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

It returns the data array like this:它返回这样的数据数组:

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

But now I dont know how to continue from here to get the age -value of Max.但是现在我不知道如何从这里继续获得 Max 的age值。 It's important in this case not to select just the second array element of data because the order can vary.在这种情况下,重要的是不要 select 只是data的第二个数组元素,因为顺序可能会有所不同。 What can I do?我能做些什么?

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

You could use the RxJS map operator with Array#find method您可以将 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);

So the stream would look like所以 stream 看起来像

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

If you do not know if the properties would always be available (which might lead to undefined errors), you could use the optional chaining operator ?.如果您不知道属性是否始终可用(这可能会导致undefined的错误),您可以使用可选的链接运算符?. . .

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

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