Reputation: 43
Say I have an object:
var obj1 = {var1: 123, var2: 456, var3: "fdsfdsfds"};
How can I create object 2 based on obj1 so that it has all the properties of obj1 and they all belong to other new key:
var obj2 = {parentKey: {var1: 123, var2: 456, var3: "fdsfdsfds"}};
The names of the keys -- var1, var2, var3 -- aren't known and they can be anything.
Upvotes: 0
Views: 74
Reputation: 1082
In fact it is you is not using compiler like babel or other, it is necessary to use the following syntax:
var obj2 = {parentKey: Object.assign ({}, obj1)};
If you do not want your object to be immutable, you just have to do:
var obj2 = {parentKey: obj1};
Waiting for the standardization of ES2015, you must use a compiler to use this syntax:
const obj1 = {var1: 123, var2: 456, var3: "fdsfdsfds"};
const obj2 = {... obj1};
Upvotes: 1
Reputation: 1074305
If you really need to copy the object, a simple way to do a simple-minded copy is the new Object.assign
function (which can be shimmed for older environments);
var obj2 = {parentKey: Object.assign({}, obj1)};
If you don't mind using the same object (not a copy), you can just make it the value of the new object's parentKey
:
var obj2 = {parentKey: obj1};
Upvotes: 1