Splitting an object into an array of objects in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an object like this −

const obj = {
   "value 0": "value",
   "value 1": "value",
   "value 2": "value",
   "value 3": "value",
   "value 4": "value",
   "value 5": "value",
   "value 6": "value",
   "value 7": "value",
   "value 8": "value",
   "value 9": "value"
};

We are required to write a JavaScript function that takes in one such object. The function should return a new array of objects in which each key/value pair is separated into its own separate object.

Example

The code for this will be −

const obj = {
   "value 0": "value",
   "value 1": "value",
   "value 2": "value",
   "value 3": "value",
   "value 4": "value",
   "value 5": "value",
   "value 6": "value",
   "value 7": "value",
   "value 8": "value",
   "value 9": "value"
};
const separateObject = obj => {
   const res = [];
   const keys = Object.keys(obj);
   keys.forEach(key => {
      res.push({
         key: obj[key]
      });
   });
   return res;
};
console.log(separateObject(obj));

Output

And the output in the console will be −

[
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' }
]
raja
Published on 21-Nov-2020 14:18:49
Advertisements