Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Object to array - JavaScript
Suppose, we have an object of key value pairs like this −
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
We are required to write a function that takes in the object and returns an array of arrays with each subarray representing one key value pair
Example
Let’s write the code for this function −
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
const objectToArray = obj => {
const keys = Object.keys(obj);
const res = [];
for(let i = 0; i < keys.length; i++){
res.push([keys[i], obj[keys[i]]]);
};
return res;
};
console.log(objectToArray(obj));
Output
The output in the console: −
[ [ 'name', 'Vikas' ], [ 'age', 45 ], [ 'occupation', 'Frontend Developer' ], [ 'address', 'Tilak Nagar, New Delhi' ], [ 'experience', 23 ], [ 'salary', '98000' ] ]
Advertisements