By direct renaming
In this approach, we will generate a new object by repeatedly iterating over the key-value pairs of the previous(original) object. With the help of the ternary operator adding in the loop, it will conditionally assign the intended new key based on the original key.
Example: This example shows the implementation of the above-explained approach.
Javascript
const originalObj = { name: "John" , age: 30 }; const renamedObj = {}; for (const key in originalObj) { const newKey = key === "name" ? "fullName" : key; renamedObj[newKey] = originalObj[key]; } console.log(renamedObj); |
{ fullName: 'John', age: 30 }
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.