Problem I have a Javascript array and I'm trying to return only the key:value pairs that match a specific key in the most efficient way possible.
I've tried using a Foreach loop and pushing each key:value to a new array but that seems like an inefficient way to do it and overly complex.
Code
initialArray = [ { friends: [],
otherFriends: [],
_id: 5c6c7132f9bf4bdab9c906ff,
user: 5c65d9438e4a834c8e85dd7d,
password: '$2b$10$LMFB6CBdwxSAfjog/Uo3t.u/G0GBtzfJnYdpvlrSNchA9.jlNOdAa',
email: '[email protected]',
createdAt: 2019-02-19T21:12:18.569Z,
updatedAt: null,
online: false,
__v: 0 },
{ friends: [],
otherFriends: [],
_id: 5c6ccd6d3a0dc4e4951c2bee,
user: 5c65d9438e4a834c8e85dd7e,
password: '$2b$10$gEAbOAdKyHJfAksr5txUNOudCautRs1w/pubplQKzZ5PefhfOOEhq',
email: '[email protected]',
createdAt: 2019-02-20T03:45:49.703Z,
updatedAt: null,
online: false,
__v: 0 } ]
Desired Array
[
{ user: 5c65d9438e4a834c8e85dd7d },
{ user: 5c65d9438e4a834c8e85dd7e }
]
Current Method
const newArray = []
initialArray.forEach(element => {
newArray.push({key: element.user});
});
If anyone has any suggestions that would be amazing! Thanks in advance :)
MyModel.find({}, 'user');MyModel.find({}, {'user': 1, '_id': 0});'