By using Higher-Order Functions
In this approach, we will rename the object key with the help of Higher-order functions, such as map, which is used to loop through and modify the object entries. The mapping function uses a ternary operator to conditionally determine the new key name during conversion.
Example: This example shows the implementation of the above-explained approach.
Javascript
const originalObj = { city: "Kanpur" , state: "UP" }; const renamedObj = Object.fromEntries( Object.entries(originalObj).map(([key, value]) => (key === "city" ? [ "PresentCity" , value] : [key, value])) ); console.log(renamedObj); |
{ PresentCity: 'Kanpur', state: 'UP' }
How to Rename an Object Key by the use of the Ternary Operator in JavaScript ?
Renaming object keys in JavaScript is a crucial task. To conduct key renaming conditionally, the ternary operator offers a succinct solution. Using the ternary operator, will provide versatility, especially in complicated circumstances, and enhance readability and maintainability into account when using this method for key renaming.