Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- // Removes unwanted properties and adds undefined properties with default values
- const defaultObject = (obj, defaultProperties) => {
- const defaultKeys = Object.keys(defaultProperties);
- // Remove unwanted keys
- Object.keys(obj).forEach(key => {
- if (!defaultKeys.includes(key))
- delete obj[key];
- });
- // Add missing keys
- defaultKeys.forEach(key =>
- obj[key] = typeof obj[key] === 'undefined' ? defaultProperties[key] : obj[key]
- );
- return obj;
- };
- // Example
- console.log(defaultObject(
- {
- a: 'a',
- b: 'b',
- },
- {
- b: 'a',
- c: 'c'
- }
- ));
- /*
- Changes first object to; and returns:
- {
- b: 'b',
- c: 'c'
- }
- */
Add Comment
Please, Sign In to add comment