showing results for - "delete object not working"
Louisa
14 Jul 2018
1// define dis-allowed keys and values
2const disAllowedKeys = ['_id','__v','password'];
3const disAllowedValues = [null, undefined, ''];
4
5// our object, maybe a Mongoose model, or some API response
6const someObject = {
7  _id: 132456789,
8  password: '$1$O3JMY.Tw$AdLnLjQ/5jXF9.MTp3gHv/',
9  name: 'John Edward',
10  age: 29,
11  favoriteFood: null
12}; 
13
14// use reduce to create a new object with everything EXCEPT our dis-allowed keys and values!
15const withOnlyGoodValues = Object.entries(someObject).reduce((ourNewObject, pair) => {
16  const key = pair[0];
17  const value = pair[1]; 
18  if (
19    disAllowedKeys.includes(key) === false &&
20    disAllowedValues.includes(value) === false
21  ){
22    ourNewObject[key] = value; 
23  }
24  return ourNewObject; 
25}, {}); 
26
27// what we get back...
28// {
29//   name: 'John Edward',
30//   age: 29
31// }
32
33// do something with the new object!
34server.sendToClient(withOnlyGoodValues);
35