Open In App

How to Rename an Object Key by the use of the Ternary Operator in JavaScript ?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

These are the following approaches

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


Output

{ fullName: 'John', age: 30 }

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


Output

{ PresentCity: 'Kanpur', state: 'UP' }

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 }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads