I have a JavaScript object as follows:
var a = { Prop1: \'test\', Prop2: \'test2\' }
How would I change the \"property name\" of Prop1 to P
Using the proposed property rest notation, write
const {Prop1, ...otherProps} = a;
const newObj = {Prop3: Prop1, ...otherProps};
This is supported by Babel's object rest spread transform.
That isn't directly possible.
You can just write
a.Prop3 = a.Prop1;
delete a.Prop1;
Convert your Object
to a String
using JSON.stringify
, then replace any occurrences of Prop1
with Prop3
using str.replace("Prop1", "Prop3")
.
Finally, convert your string back to an Object
using JSON.parse(str)
.
Note: str.replace("Prop1", "Prop3")
will only replace the first occurrence of "Prop1" in the JSON string. To replace multiple, use this regex syntax instead:
str.replace(/Prop1/g, "Prop3")
Refrence Here
http://jsfiddle.net/9hj8k0ju/
var a = { Prop1: 'test', Prop2: 'test2' }
str = JSON.stringify(a);
str = str.replace("Prop1","Prop3");
var converted = JSON.parse(str);
Adding to the object rest spread solution
const { Prop1: Prop3, ...otherProps } = a;
const newObj = { Prop3, ...otherProps };