ani
ani

Reputation: 516

how to rename the property in an object using javascript

The question may seems like duplicate but there is a difference . i am trying to give new key which doesn't have any space.

{order_id :"123" , order_name : "bags" , pkg_no : "00123#"}

i want to rename the key as below

{Order Id : "123" , Order Name : "bags" , Package : "00123#" }

Upvotes: 1

Views: 1107

Answers (2)

kuzditomi
kuzditomi

Reputation: 730

you can use the index notation to use keys like that.

obj['Order Id'] = obj.order_id;

and you can use delete eg. to remove old keys

delete obj.order_id;

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

There doesnt seem to be any obvious way to rename automatically (mostly because of pkg_no --> Package), so the best you could do is have a mapping from one property name to the other and use that to reconfigure your object.

const input = {order_id :"123" , order_name : "bags" , pkg_no : "00123#"}
const newProps = {order_id:"Order Id",order_name:"Order Name", pkg_no:"Package"};

const result = Object.fromEntries(Object.entries(input).map( ([key,value]) => [newProps[key],value]))
console.log(result);

Upvotes: 3

Related Questions