Object to array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
]
raja
Published on 15-Sep-2020 09:13:11
Advertisements