Return entire object not just key in js with filter

Issue

I currently have some data in a firebase db that contains multiple members like so:

membersData: {
    uid1: {
        first: 'blah'
        last: 'blah'
        mStatus: true
    }
    uid2: {
        first: 'blah'
        last: 'blah'
        mStatus: true
    }
    uid3: {
        first: 'blah'
        last: 'blah'
        mStatus: false
    }
}

To filter over my data I run this:

Object.keys(membersData).filter(member => membersData[member].mStatus == true)

However this only returns an array of the uid. How can I get it to return the uid but also the first, last and mStatus?

Solution

You are getting only the keys with Object.keys. All the further computations are done on that array of keys. You can use a .map() again to get the items in the requested format.

You might simply use a different method like Object.values() if you are only concerned about the values and not the keys:

let membersData = {
    'uid1' : {
        'first': 'blah',
        'last': 'blah',
       'mStatus': true
    },
    'uid2': {
        'first': 'blah',
        'last': 'blah',
        'mStatus': true
    },
    'uid3': {
        'first': 'blah',
        'last': 'blah',
        'mStatus': false
    }
}

let ans = Object.keys(membersData).filter(member => membersData[member].mStatus == true).map(x => { return { [x] : membersData[x]} } );

console.log(ans);

let ans2 = Object.values(membersData).filter(member => member.mStatus == true);
console.log(ans2);

Answered By – Tushar Shahi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published