Home > Software engineering >  Getting undefined result when trying to loop and filtering array
Getting undefined result when trying to loop and filtering array

Time:02-28

I am currently working with objects and arrays in nodejs in conjuction with filters. I am currenlty facing difficulty in figuring out how to properly traverse an object and filter for the desired results. Instead I am getting undefined. I have an object users and I am wanting to filter for each user configuration that has active === true and then ultimately display every users configuration with that filter in the final result. What is the right/best way to approach this? Should I use map?

Current Result:

undefined

Desired Result:

[
    {
        email: '[email protected]',
        active: true
    },
    {
        email: '[email protected]',
        active: true
    },
    {
        email: '[email protected]',
        active: true
    }
]

Code:

const users = [
    {
      name: 'User1',
      configuration: [ 
          {
            email: '[email protected]',
            active: true
          },
          {
            email: '[email protected]',
            active: false
          }
      ],
    },
    {
      name: 'User2',
      configuration: [ 
          {
            email: '[email protected]',
            active: true
          },
          {
            email: '[email protected]',
            active: true
          }
      ],
    },
];

const result = users.forEach(user => user.configuration.filter( x => {

    let {
        active
    } = x;

    return active === true;
}));

console.log(result);

CodePudding user response:

you can use flatMap for this. forEach always returns undefined. usually if you want to return some array use map but since filter also returns an array you need to flat it to get your desired result hence flatMap

const users = [{name: 'User1',configuration: [ {email: '[email protected]',active: true},{email: '[email protected]',active: false}],},{name: 'User2',configuration: [ {email: '[email protected]',active: true},{email: '[email protected]',active: true}],},];

const result = users.flatMap(user => user.configuration.filter( x => x.active===true));

console.log(result);

  • Related