By using conditional Renaming Based on Value
In this appraoch, we are using ternary operator with spread operator. we are addding another key by checking the condition and printing the newly formed object into the console.
Example: This example shows the implementation of the above-explained approach.
Javascript
const product = { name: "T-Shirt" , price: 20, discount: 10 }; const renamedProduct = { ...product, [product.discount > 0 ? "discountedPrice" : "price" ]: product.price, }; console.log(renamedProduct); |
Output
{ name: 'T-Shirt', price: 20, discount: 10, discountedPrice: 20 }
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.
Contact Us