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';
}
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;
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.
Adding to the object rest spread solution
const { Prop1: Prop3, ...otherProps } = a;
const newObj = { Prop3, ...otherProps };
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