Home > Net >  Get value of key in nested array of objects (RxJS Observable)
Get value of key in nested array of objects (RxJS Observable)

Time:12-10

Through my observable testData$ I receive data that looks like this:

      [
        {
          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$. 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. It's important in this case not to select just the second array element of data because the order can vary. What can I do?

CodePudding user response:

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

CodePudding user response:

You could use the RxJS map operator with Array#find method

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

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 ?..

  • Related