71

I have a JavaScript object as follows:

var a = { 
 Prop1: 'test', 
 Prop2: 'test2' 
}

How would I change the property name of Prop1 to Prop3?

I tried the following code but it didn't work...

for (var p in r){
  p.propertyName = 'Prop3';
}
Gass
  • 7,536
  • 3
  • 37
  • 41
firebird
  • 3,461
  • 6
  • 34
  • 45
  • 8
    I guess I'll be the one to say it this time. `var a = { Prop1: 'test', Prop2: 'test2' }` isn't JSON data. It's a JavaScript object literal that could be translated into JSON data if you chose to do so. – RightSaidFred Dec 13 '11 at 02:02
  • - You can use a utility to handle this. https://stackoverflow.com/a/60677446/6512565 – Muhammed Moussa Mar 13 '20 at 21:31

3 Answers3

120

That isn't directly possible.

You can just write

a.Prop3 = a.Prop1;
delete a.Prop1;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
34

Another approach would be to use the proposed property rest notation like so:

const {Prop1, ...otherProps} = a;
    
const newObj = {Prop3: Prop1, ...otherProps};

This is supported by Babel's object rest spread transform.

Gass
  • 7,536
  • 3
  • 37
  • 41
13

Adding to the object rest spread solution

const { Prop1: Prop3, ...otherProps } = a;
const newObj = { Prop3, ...otherProps };
kendotwill
  • 1,892
  • 18
  • 17