

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Replacing array of object property name in JavaScript
- Sort object array based on another array of keys - JavaScript
- Update JavaScript object with another object, but only existing keys?
- Check if object contains all keys in JavaScript array
- Return an array with numeric keys PHP?
- PHP print keys from an object?
- Search a value in an object with number keys with MongoDB
- Recursively list nested object keys JavaScript
- Replacing spaces with underscores in JavaScript?
- How to set dynamic property keys to an object in JavaScript?
- Fetching object keys using recursion in JavaScript
- Filter nested object by keys using JavaScript
- Make strings in array become keys in object in a new array in JavaScript?
- Filter an object based on an array JavaScript
- Replacing zero starting with whitespace in JavaScript
Advertisements