- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting an object into an array of objects in JavaScript
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' } ]
Advertisements