- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'};
Example
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); console.log(obj);
Output
The output in the console −
{ 'First Name': 'john', age: 18, country: 'USA' }
- Related Articles
- Replacing array of object property name in JavaScript
- Sort object array based on another array of keys - JavaScript
- Check if object contains all keys in JavaScript array
- How to unflatten an object with the paths for keys in JavaScript?
- Update JavaScript object with another object, but only existing keys?
- Return an array with numeric keys PHP?
- Make strings in array become keys in object in a new array in JavaScript?
- Search a value in an object with number keys with MongoDB
- Recursively list nested object keys JavaScript
- How to set dynamic property keys to an object in JavaScript?
- Replacing spaces with underscores in JavaScript?
- PHP print keys from an object?
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- Fetching object keys using recursion in JavaScript
- Filter nested object by keys using JavaScript

Advertisements