Guest User

Untitled

a guest
Jun 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. 'use strict';
  2.  
  3. // Removes unwanted properties and adds undefined properties with default values
  4. const defaultObject = (obj, defaultProperties) => {
  5. const defaultKeys = Object.keys(defaultProperties);
  6. // Remove unwanted keys
  7. Object.keys(obj).forEach(key => {
  8. if (!defaultKeys.includes(key))
  9. delete obj[key];
  10. });
  11. // Add missing keys
  12. defaultKeys.forEach(key =>
  13. obj[key] = typeof obj[key] === 'undefined' ? defaultProperties[key] : obj[key]
  14. );
  15. return obj;
  16. };
  17.  
  18. // Example
  19. console.log(defaultObject(
  20. {
  21. a: 'a',
  22. b: 'b',
  23. },
  24. {
  25. b: 'a',
  26. c: 'c'
  27. }
  28. ));
  29.  
  30. /*
  31. Changes first object to; and returns:
  32. {
  33. b: 'b',
  34. c: 'c'
  35. }
  36. */
Add Comment
Please, Sign In to add comment