73

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'; } 
2
  • 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. Commented Dec 13, 2011 at 2:02
  • - You can use a utility to handle this. stackoverflow.com/a/60677446/6512565 Commented Mar 13, 2020 at 21:31

4 Answers 4

120

That isn't directly possible.

You can just write

a.Prop3 = a.Prop1; delete a.Prop1; 
Sign up to request clarification or add additional context in comments.

4 Comments

the delete function is usually frowned upon for its performance. Would not it be better to recreate an object?
@Dmitry: only ask yourself this question if you realize your app is slow because you're using delete. Also I guess creating a new object might be longer if there are lots of properties.
@user276648: Plus GC churn.
@Dmitry what are the downsides of using 'delete'?
37

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.

Comments

15

Adding to the object rest spread solution

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

Comments

-1

A simple way to do this is by using if():

for (key in a){ if (key == "Prop1") { key = "Prop3"; } } 

You can use strict equality === too, making no difference as you will use a string nevertheless

1 Comment

Dear @Lefteris, are you a) joking, or b) something else? And before you get all worked up with this quest of mine to eradicate this kind of answer, here's my usual advice: TRY YOUR OWN CODE BEFORE YOU POST IT!!! It's wildly evident that this will not work, because you're just changing the cycle variable key's value, not the actual object a's property name. Automagic is not part of the coding game, and assignment — as occurs on the for variable key during cycle — is a one-way thing. Always always always try your code before posting.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.