I wanna know if it is possible to change the property name of a json
For example I have {"lat":27.4924,"lon":77.6737}
and I want to change lon with lng , so like this {"lat":27.4924,"lng":77.6737}
I wanna know if it is possible to change the property name of a json
For example I have {"lat":27.4924,"lon":77.6737}
and I want to change lon with lng , so like this {"lat":27.4924,"lng":77.6737}
Using delete operator
.
let obj = {"lat":27.4924,"lon":77.6737}
obj.lng = obj.lon;
delete obj.lon;
console.log(obj)
One more way is to use destructing assignment
let obj = {"lat":27.4924,"lon":77.6737, 'xyz':2}
let {lon:lng,...rest} = obj
let obj1 = {...rest,lng}
console.log(obj1)
Using reduce also you can do
let obj = {"lat":27.4924,"lon":77.6737}
let op = Object.keys(obj).reduce((op,cur)=>{
if(cur == 'lon'){
op['lng'] = obj[cur]
} else {
op[cur] = obj[cur]
}
return op
},{})
console.log(op)
A funny way to do it would be to stringify the json and replace the string.
JSON.parse(JSON.stringify(jsn).replace("lon", "lng"))
You can try this method. You assign the value of old property to new property and delete old one. using delete
. I have created a function for that
let obj = {"lat":27.4924,"log":77.6737}
function changePropName(obj,oldName,newName){
obj[newName] = obj[oldName];
delete obj[oldName];
}
changePropName(obj,'log','newName');
console.log(obj)