0

I want to create a copy of a JavaScript object which has enumerable and non-enumerable properties. I want make a exact replica of the object with all enumerable and non-enumerable properties copied to the new one.

Any help how can it be done?

Vipul
  • 566
  • 5
  • 29

2 Answers2

1
JSON.parse(JSON.stringify(obj))
Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288
  • already tried it but it did not solve the purpose. object which i want to copy is a nested one, which has a copy of several other objects in it – Vipul Apr 19 '15 at 05:00
0

You should use Object.create or it's backward compatible counterpart.

if(!Object.create){
  Object.create = function(o){
    function F(){}; F.prototype = o;
    return new F;
  }
}
var oldObj = {prop1:'val1', prop2:'val2', prop3:'val3'};
var newObj = Object.create(oldObj);
delete newObj.prop2;
console.log(newObj); console.log(oldObj);
StackSlave
  • 10,613
  • 2
  • 18
  • 35