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'; } That isn't directly possible.
You can just write
a.Prop3 = a.Prop1; delete a.Prop1; delete function is usually frowned upon for its performance. Would not it be better to recreate an object?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.
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
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.
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.