How to replace the names of multiple object keys with the values provided using JavaScript ?
Last Updated :
12 Jan, 2022
The following approach covers how to replace the names of multiple object keys with the values provided by the user using JavaScript.
Problem Statement: You are given an object which contains different key-value pairs in which key symbolizes the property and value itself is known as the property value, and you need to change one or more key's original name with the name provided by the user using JavaScript.
As an example take the above-illustrated object initially. This object contains key-value pairs like Name: "Hello" and so on. So let us suppose we are targeting the Name key and further we are going to change this Name key as FirstName key name by the following approach.
Before directly jumping into the approaches to solve the above-illustrated problem, let us first declare the object which we are going to use to solve the query.
Example: By using the following syntax let's first create an object:
JavaScript
<script>
let object = {
name: "Hello",
age: 20,
gender: "Male",
};
console.log(object);
</script>
Output:
{ name: 'Hello', age: 20, gender: 'Male' }
Now let us see the approaches to solve the above-illustrated problem.
Approach 1:
- This is the native approach and quite a simple one too.
- In this approach we will directly pick up the object key and will change the name of that picked key with the name provided by the user.
- After providing the key name we will then delete the previously declared one and replace it with new one.
- We will write the logic part in a method (or function) and further will call that method which will execute our result.
Example 1:
JavaScript
<script>
let object = {
name: "Hello",
age: 20,
gender: "Male",
};
let renmeObjectKey = (object) => {
object.FirstName = object.name;
delete object.name;
};
renmeObjectKey(object);
console.log(object);
</script>
Output:
{ age: 20, gender: 'Male', FirstName: 'Hello' }
Now suppose you want to target age key in the object with name provided by yourself.
Example 2:
JavaScript
<script>
let object = {
name: "Hello",
age: 20,
gender: "Male",
};
let renmeObjectKey = (object) => {
object.FirstName = object.name;
object.currentAge = object.age;
delete object.name;
delete object.age;
};
renmeObjectKey(object);
console.log(object);
</script>
Now along with the name key, age key is also replaced with the new name provided by the user.
Output:
{ gender: 'Male', FirstName: 'Hello', currentAge: 20 }
Note: The only thing you could notice here is that the position of the object gets changed, but its value remains preserved and same too.
Approach 2:
- In this approach we will declare a method which is completely responsible for executing our result.
- Inside the parameters of this method, we will pass in two arguments, first one is keysMap object which we will accept it from user that actually contains the new key name which will be going to replace from the previous key name and second one is the object which we are referring to.
- Now inside that method we will use Object.keys() which will accept our object initially and will target all our object keys, and then we will execute reduce() over it which will accept two things: first is accumulator value which will act as our result variable and second one is the key which we are targeting currently.
- Then afterwards we will write our logic part and for that we will first take into our account of spread operator which will spread our object into an array, and then we will render out the object keys and replace it with own passed key name.
- Then later we will pass our method inside a new variable which we will declare as our result variable and then will console.log() our result.
Example:
JavaScript
<script>
let object = {
name: "Hello",
age: 20,
gender: "Male",
};
let renameKeys = (keysMap, object) =>
Object.keys(object).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: object[key] },
}),
{}
);
let result = renameKeys({ name: "FirstName" }, object);
console.log(result);
</script>
Output:
{ FirstName: 'Hello', age: 20, gender: 'Male' }
Note: This approach will preserve the position of the key and also the value.
Similar Reads
How to Get all Property Values of a JavaScript Object without knowing the Keys?
To get all property values from a JavaScript object without knowing the keys involves accessing the object's properties and extracting their values.Below are the approaches to get all property values of a JavaScript Object:Table of ContentUsing Object.values() MethodUsing Object.keys() methodApproac
2 min read
How to add a property to a JavaScript object using a variable as the name?
In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability. There are several methods that can be used to add a property to a JavaScript objec
2 min read
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 u
2 min read
How to unflatten an object with the paths for keys in JavaScript ?
In this article, we will learn to unflatten an object which has a certain number of key-value pairs(s) within it with the paths for the keys in JavaScript. Problem Statement: You are given an object with several key-value pair(s). Some keys have various keys names present after a dot, you basically
4 min read
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript s
2 min read
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key na
4 min read
How to create an object from the given key-value pairs using JavaScript ?
In this article, we will learn to create an object from the given key-value pairs using JavaScript.Key-value pair: Unique identifier (key) associated with its corresponding value; fundamental for data organization and retrieval in programming. here we have some common approaches.We will explore the
5 min read
How to Swap Two Array of Objects Values using JavaScript ?
Swapping values between two arrays of objects is a common operation in JavaScript, there are multiple methods to swap values between arrays of objects efficiently. Swapping values between arrays can be useful in scenarios like reordering data, shuffling items, or performing certain algorithms. These
6 min read
How to add Key-Value pair to a JavaScript Object?
A JavaScript object has a key-value pair, and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods.Below are the methods to add a key/value pair to a JavaScript object:Table of ContentUsing Dot NotationUsing Bracket
4 min read
How to remove a key-value pair from JavaScript object?
Removing a key-value pair from an object in JavaScript means deleting a specific property and its corresponding value from the object. This can be achieved using the delete operator, destructuring with the rest operator, or various utility functions to manipulate the object dynamically.How to remove
3 min read