Open In App

How to replace the names of multiple object keys with the values provided using JavaScript ?

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:




<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: 

Example 1: 




<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: 




<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: 

Example: 




<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.


Article Tags :