Split keys and values into separate objects - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 }
]
raja
Published on 30-Sep-2020 14:12:33
Advertisements