Set Object Default Values.

Posted by fsanren on March 30, 2023

Set Object Default Values

setDefaultValues

function setDefaultValues(obj, defaultObj) {
  for (let [key, value] of Object.entries(defaultObj)) {
    if (obj[key] === null || obj[key] === undefined) {
      obj[key] = value;
    } else if (typeof value === 'object' && typeof obj[key] === 'object') {
      setDefaultValues(obj[key], value);
    }
  }
  return obj;
}

Here’s an example usage of this function:

const myObj = {
    prop1: null,
    prop2: 'Value2',
    prop3: {
        subprop1: null,
        subprop2: 'Subvalue2',
    },
};

const defaultObj = {
    prop1: 'Value1',
    prop2: 'Value2',
    prop3: {
        subprop1: 'Subvalue1',
        subprop2: 'Subvalue2',
        subprop3: 'Subvalue3',
    },
};

const result = setDefaultValues(myObj, defaultObj);

console.log(result); // Output: { prop1: 'Value1', prop2: 'Value2', prop3: { subprop1: 'Subvalue1', subprop2: 'Subvalue2', subprop3: 'Subvalue3' } }