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
Split keys and values into separate objects - JavaScript
In JavaScript, you often need to transform an object into an array of objects where each key-value pair becomes a separate object. This is useful for data processing, API responses, and working with libraries that expect array formats.
Problem Statement
Suppose we have an object like this:
const dataset = {
"diamonds": 77,
"gold-bars": 28,
"exciting-stuff": 52,
"oil": 51,
"sports-cars": 7,
"bitcoins": 40
};
We need to write a JavaScript function that takes this object and returns an array of objects with keys and values split into separate properties.
The expected output should be:
[
{"asset": "diamonds", "quantity": 77},
{"asset": "gold-bars", "quantity": 28},
{"asset": "exciting-stuff", "quantity": 52},
{"asset": "oil", "quantity": 51},
{"asset": "sports-cars", "quantity": 7},
{"asset": "bitcoins", "quantity": 40}
]
Using Object.keys() with for Loop
const dataset = {
"diamonds": 77,
"gold-bars": 28,
"exciting-stuff": 52,
"oil": 51,
"sports-cars": 7,
"bitcoins": 40
};
const splitKeyValue = obj => {
const keys = Object.keys(obj);
const res = [];
for(let i = 0; i
[
{ asset: 'diamonds', quantity: 77 },
{ asset: 'gold-bars', quantity: 28 },
{ asset: 'exciting-stuff', quantity: 52 },
{ asset: 'oil', quantity: 51 },
{ asset: 'sports-cars', quantity: 7 },
{ asset: 'bitcoins', quantity: 40 }
]
Using Object.entries() with map()
A more concise approach using modern JavaScript features:
const dataset = {
"diamonds": 77,
"gold-bars": 28,
"exciting-stuff": 52,
"oil": 51,
"sports-cars": 7,
"bitcoins": 40
};
const splitKeyValueModern = obj => {
return Object.entries(obj).map(([key, value]) => ({
asset: key,
quantity: value
}));
};
console.log(splitKeyValueModern(dataset));
[
{ asset: 'diamonds', quantity: 77 },
{ asset: 'gold-bars', quantity: 28 },
{ asset: 'exciting-stuff', quantity: 52 },
{ asset: 'oil', quantity: 51 },
{ asset: 'sports-cars', quantity: 7 },
{ asset: 'bitcoins', quantity: 40 }
]
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| Object.keys() + for loop | More verbose | Traditional | Slightly faster |
| Object.entries() + map() | Concise | Modern, cleaner | Good |
Common Use Cases
This pattern is commonly used for:
- Converting objects to arrays for chart libraries
- Preparing data for API requests
- Transforming configuration objects
- Creating table data from key-value pairs
Conclusion
Both approaches effectively split object keys and values into separate objects. The Object.entries() method provides cleaner, more readable code, while the traditional for loop approach offers slightly better performance for large datasets.
