Reduce key value pairs in a javascript object based on a given array

I want to remove unnecessary key values pairs in a user object based on an array, essentially a whitelist. I have looked at reduce(), filter() and map() but can't quite get the implementation to work.

Here is my code currently

const user = {
   "email": "hello@me.com"
   "name": "Bob"
   "surname": "Smith"
};

const userFields = [`email`, `name`]; // array of whitelist

Before I iterate through the object properties, I'd like to reduce Object to have fields only in the array whitelist, so our man Bob Smith would end up like this

const user = {
  "email": "hello@me.com" 
  "name": "Bob"
};

Thanks!



Read more here: https://stackoverflow.com/questions/65722979/reduce-key-value-pairs-in-a-javascript-object-based-on-a-given-array

Content Attribution

This content was originally published by Shwmae at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: