1

I am trying to change only the value of copied object, not the main but both objects change as of the result of running this code.

const Randomdata = {
  a: 10,
  b: 5,
  c: {
    f: "value1",
    q: "value2"
  }
};

function copy(MainObj) {
  let ObjCopy = {};
  for (let key in MainObj) {
    ObjCopy[key] = MainObj[key];
  }

  return ObjCopy;
}

const newObj = copy(Randomdata);

Randomdata.c.q = "value3";

console.log(newObj);
console.log(Randomdata);
brk
  • 48,835
  • 10
  • 56
  • 78
Siyavush
  • 77
  • 6
  • Use `JSON.parse(JSON.stringify(Randomdata ))` – brk Apr 03 '21 at 07:12
  • Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Sebastian Simon Apr 03 '21 at 07:16

1 Answers1

0

Though JSON.parse and JSON.stringify will work , but you will need a recusive function if want to achieve the same result using for..in. The reason is value of key c is a object and when you are copying it, it is just referencing to the old copy

const Randomdata = {
  a: 10,
  b: 5,
  c: {
    f: "value1",
    q: "value2"
  }
};

function copy(MainObj, ObjCopy) {
  for (let key in MainObj) {
    // check if the value is a object , if so then 
    // reclusively call the same function
    if (typeof MainObj[key] === 'object') {
      copy(MainObj[key], ObjCopy)
    } else {
      ObjCopy[key] = MainObj[key];
    }
  }
  return ObjCopy;
}

const newObj = copy(Randomdata, {});

Randomdata.c.q = "value3";

console.log(newObj);
console.log(Randomdata);
brk
  • 48,835
  • 10
  • 56
  • 78