Converting object to 2-D 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' ]
];

Updated on: 10-Dec-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements