JavaScript: replacing object keys with an array

We are required to write a JavaScript function that takes in an object and an array of literals.

The length of the array and the number of keys in the object will always be equal. Our function should replace the corresponding keys of the object with the element of the array.

For example: If the input array and object are −

const arr = ['First Name', 'age', 'country'];
const obj = {'name': 'john', 'old': 18, 'place': 'USA'};

Then the output should be −

const output = {'First Name': 'john', 'age': 18, 'country': 'USA'};


The code for this will be −

const arr = ['First Name', 'age', 'country'];
const obj = {'name': 'john', 'old': 18, 'place': 'USA'};
const replaceKeys = (arr, obj) => {
   const keys = Object.keys(obj);
   const res = {};
   for(let a in arr){
      res[arr[a]] = obj[keys[a]];
      obj[arr[a]] = obj[keys[a]];
      delete obj[keys[a]];
replaceKeys(arr, obj);


The output in the console −

{ 'First Name': 'john', age: 18, country: 'USA' }

Updated on: 10-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started