Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript object to array of individual objects

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!!

like image 219
dc0087 Avatar asked Jun 10 '16 04:06

dc0087


2 Answers

Use Array#forEach over Object.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);
like image 86
Rayon Avatar answered Oct 16 '22 09:10

Rayon


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);
like image 33
Nina Scholz Avatar answered Oct 16 '22 07:10

Nina Scholz