-3

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}

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • 5
    `foo.lng = foo.lon; delete foo.lon;` – epascarello Feb 04 '19 at 19:08
  • Possible duplicate of [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) and [Modify object's keys without creating new object](https://stackoverflow.com/questions/25929400) – adiga Feb 04 '19 at 19:32

3 Answers3

2

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

A funny way to do it would be to stringify the json and replace the string.

JSON.parse(JSON.stringify(jsn).replace("lon", "lng"))
Borisu
  • 828
  • 7
  • 15
0

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73