Home > Software engineering >  how to deep copy a JavaScript object from another without adding new properties
how to deep copy a JavaScript object from another without adding new properties

Time:03-11

Here I have a default object with nested properties for eg -

default = { 
key1: val1;
key2: {
  key3: val3,
  key4: val4
  }
}

and a new object with new values for same properties as above and some extra properties of its own

newObject = {
key1: val11,
key2: {
  key3: val31,
  key5: val51,
  }
}

Now I need to replace all the available nested properties of default with newObject without adding any new property to default. The skeleton of default should never change. Also this needs to be a deep copy. So the result here should look like:

result = { 
key1: val11;
key2: {
  key3: val31,
  key4: val4,
  }
}

CodePudding user response:

I added code for you but if you need more complex then you may want to use some js packages, but I think it should be sufficient.

Here you go:

let objectDefault = {
      key1: 'val1',
      key2: {
        key3: 'val3',
        key4: 'val4'
      }
    }
    
let otherObject = {
  key1: 'val5',
  key2: {
    key3: 'val6',
    key4: 'val7'
  },
  key10: 'test'
}

let filteredValuesOfOthedObject = Object.fromEntries(Object.entries(otherObject).filter(([key]) => Object.keys(objectDefault).includes(key)));

let newObject = {...objectDefault, ...filteredValuesOfOthedObject}

console.log(newObject)

CodePudding user response:

Take a look at this one. // Parent Object let _default = { key1: 'val1', key2: { key3: 'val3', key4: 'val4', key6: { key7: 'test', key10: 'val10' } }, key11: 'val231' };

// Output object
let newObj = {
    key1: 'val11',
    key2: {
        key3: 'val31',
        key5: 'val51',
        key6: {
            key7: 'val31',
            key8: 'val43'
        },
        key12: 'val212'
    }
};

// Utils to check if value if object
function isObject(value) {
    return typeof (value) === 'object' && !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}

// Recursive function to add 
function recursive(obj, ouputObj) {
    Object.keys(obj).map((el, i) => {
        let val = obj[el];
        if (!ouputObj?.[el]) ouputObj[el] = val;
        if (isObject(val)) recursive(val, ouputObj?.[el] || {});
    })
    return ouputObj;
}

newObj = recursive(_default, newObj);
console.log(`~~~~~~~~~~~~~~~, `, newObj);
  • Related