Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split keys and values into separate objects - JavaScript
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 are required to write a JavaScript function that takes one such object and returns an array of objects that have keys and their values splitted.
Therefore, for the above object, the output should be −
const output = [
{"asset":"diamonds", "quantity":77},
{"asset":"gold-bars", "quantity":28},
{"asset":"exciting-stuff", "quantity":52},
{"asset":"oil", "quantity":51},
{"asset":"bitcoins", "quantity":40}
];
Example
Following is the code −
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 < keys.length; i++){
res.push({
'asset': keys[i],
'quantity': obj[keys[i]]
});
};
return res;
};
console.log(splitKeyValue(dataset));
Output
This will produce the following output on console −
[
{ 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 }
]Advertisements