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' ]
]

Updated on: 15-Sep-2020

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements