2

For example I want something like:

{ 
  a: 1,
  b: 2,
  c: 3
}

turned into:

{
  d: { 
       a: 1,
       b: 2,
       c: 3
     }
}

I've tried assigning a new property to that object with the object itself but it shows up as circular so I figure it's a reference instead of the actual properties instead of the actual values. I want to try something like JSON.stringify the object and assign it to the property but I don't know how to turn that string into an object format that I can assign to the property.

David Lin
  • 47
  • 4

3 Answers3

2
let firstObj = { 
  a: 1,
  b: 2,
  c: 3
}

let secondObj =  {};
secondObj.d = firstObj;
console.log(secondObj);

Basically you create a new object and assign the original object to its property d.

Katie.Sun
  • 711
  • 3
  • 15
1

You can use ES6 destructuting to make a shallow copy of the object and put it on a new prop:

let obj = { 
    a: 1,
    b: 2,
    c: 3
}
obj.d = {...obj}

console.log(obj)

If that's not an option you can reduce() over the objects keys to make a new object and assign it to d:

let obj = { 
    a: 1,
    b: 2,
    c: 3
}

obj.d = Object.keys(obj).reduce((newObj, k) => {
    newObj[k] = obj[k]
    return newObj
},{})

console.log(obj)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

It depends whether you want to make the deep or shallow copy of the object d. (Can the object d have a nested structure?)

The question about efficient ways to clone the object has already been answered here.