
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
Convert Object to 2D Array in JavaScript
Suppose we have an object that contains information about the weather of a city −
const obj = { city: "New Delhi", maxTemp: 32, minTemp: 21, humidity: 78, aqi: 456, day: 'Tuesday', };
We are required to write a JavaScript function that takes in one such object. The function should construct an array of arrays based on this object where each subarray contains exactly two properties −
the corresponding key
that key's value
Therefore, for the above object, the output should look like −
const output = [ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ];
Example
Following is the code −
const obj = { city: "New Delhi", maxTemp: 32, minTemp: 21, humidity: 78, aqi: 456, day: 'Tuesday', }; const objectToArray = (obj = {}) => { const res = []; const keys = Object.keys(obj); for(key of keys){ res.push([ key, obj[key] ]); }; return res; }; console.log(objectToArray(obj));
Output
Following is the output on console −
[ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ];
Advertisements