简体   繁体   中英

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#" }

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM