Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Splitting an object into an array of objects in JavaScript
Splitting an object into an array of separate objects is useful when you need to transform key-value pairs into individual objects for easier manipulation or iteration.
Suppose we have an object like this:
const obj = {
"name": "John",
"age": 30,
"city": "New York",
"profession": "Developer"
};
We need to write a JavaScript function that takes such an object and returns a new array where each key-value pair becomes its own separate object.
Using Object.keys() and forEach()
const obj = {
"name": "John",
"age": 30,
"city": "New York",
"profession": "Developer"
};
const separateObject = obj => {
const result = [];
const keys = Object.keys(obj);
keys.forEach(key => {
result.push({
[key]: obj[key]
});
});
return result;
};
console.log(separateObject(obj));
[
{ name: 'John' },
{ age: 30 },
{ city: 'New York' },
{ profession: 'Developer' }
]
Using Object.entries() with map()
A more concise approach using Object.entries() to get key-value pairs directly:
const obj = {
"name": "John",
"age": 30,
"city": "New York"
};
const separateObjectEntries = obj => {
return Object.entries(obj).map(([key, value]) => ({
[key]: value
}));
};
console.log(separateObjectEntries(obj));
[
{ name: 'John' },
{ age: 30 },
{ city: 'New York' }
]
Comparison
| Method | Code Length | Readability |
|---|---|---|
Object.keys() + forEach() |
Longer | More explicit |
Object.entries() + map() |
Shorter | More functional |
Common Use Cases
This technique is helpful when you need to:
- Convert configuration objects for processing
- Transform data for UI components that expect arrays
- Split large objects for parallel processing
Conclusion
Both methods effectively split objects into arrays of individual key-value objects. Choose Object.entries() with map() for cleaner, more functional code, or Object.keys() with forEach() for more explicit control.
Advertisements
