62

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
  • 4,098
  • 2
  • 13
  • 27
firebird
  • 3,281
  • 6
  • 33
  • 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

4 Answers4

112

That isn't directly possible.

You can just write

a.Prop3 = a.Prop1;
delete a.Prop1;
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
25

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
  • 4,098
  • 2
  • 13
  • 27
12

Adding to the object rest spread solution

const { Prop1: Prop3, ...otherProps } = a;
const newObj = { Prop3, ...otherProps };
kendotwill
  • 1,662
  • 17
  • 16
0

Using Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

const myObj = {
  prop1: 'asd',
  prop2: 'asd',
  prop3: 'asd'
}

const {prop1, ...rest} = myObj;

console.log({...rest})

For more info click here

Gass
  • 4,098
  • 2
  • 13
  • 27