I have the following object:
{English: 4, Math: 5, CompSci: 6}
How can I convert it to an array of objects, like:
[{English: 4}, {Math: 5}, {CompSci: 6}]
Can't find the answer anywhere. Thanks!!
Use
Array#forEachoverObject.keys(YOUR_OBJECT)
var input = {
  English: 4,
  Math: 5,
  CompSci: 6
};
var op = [];
Object.keys(input).forEach(function(key) {
  var obj = {};
  obj[key] = input[key];
  op.push(obj); //push newly created object in `op`array
});
console.log(op);
With newer JS, you could take Object.entries and map single properties.
var object = { English: 4, Math: 5, CompSci: 6 },
    array = Object.entries(object).map(([k, v]) => ({ [k]: v }));
console.log(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With