0

I want to create an object from another object but not have the first object change when I change the second object.

I hav tried:

var ojb2 = new Object(obj1); // obj1 is still bound to obj2
Var obj2 = Object.create(obj1); // does not create object at all
  • What do you mean by "from"? – Bergi Oct 10 '16 at 12:05
  • `Object.create` will successfully create an object that inherits from `obj1` – Bergi Oct 10 '16 at 12:05
  • 5
    Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Mistalis Oct 10 '16 at 12:07
  • Also: http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript – AJPerez Oct 10 '16 at 12:07
  • 1
    You should work wit *Object.assign()* to have a duplicate. In your case: *var obj2 = Object.assign({}, obj1);* – Mario Santini Oct 10 '16 at 12:07

2 Answers2

0

Object.create actually creates the object, but then puts the first object in as a prototype for the new object. This way you'll be able to use the properties and functions defined in the first object, but you can also define properties with the same names, without overwriting the first object:

var obj1 = {a: 20};
var obj2 = Object.create(obj1);
obj2.a = 10;
// obj2 = {
//    a: 10,
//    __proto__: {
//        a: 20
//    }
//}
Bálint
  • 4,009
  • 2
  • 16
  • 27
0

I'm not 100% sure that understand your question right, but you want to create an Object from another Object, right? And when you change the second one it will not change the original one? If I understand you right you can use the new Object(). Here is an example what's happened if you use it:

var obj1 = {
    asd : "asd",
    asd2 : "asd2"
};
var obj2 = new Object(obj1);
console.log(obj1); //{ asd: 'asd', asd2: 'asd2' }
console.log(obj2); //{ asd: 'asd', asd2: 'asd2' }
obj2 = {
    aasd : "aasd",
    aasd2 : "aasd2"
};
console.log(obj1); //{ asd: 'asd', asd2: 'asd2' }
console.log(obj2); //{ aasd: 'aasd', aasd2: 'aasd2' }
Kasmetski
  • 697
  • 6
  • 10