- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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' }
Advertisements