5

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

ozil
  • 6,357
  • 8
  • 29
  • 53
dc0087
  • 77
  • 1
  • 3
  • 3
    Show us what you've tried, some problems you're facing (specific ones) and we'll gladly help. – Andrew Li Jun 10 '16 at 05:00
  • To add what @AndrewL is saying, you need to show us that you actually tried something first. Show us your code that failed, and we will help you figure out why it failed and how to solve your problem. – amallard Jun 10 '16 at 05:03
  • 1
    Why do you want to do that? Also, this is pretty much a duplicate of [convert object to array of objects](http://stackoverflow.com/q/6586189/218196). – Felix Kling Jun 10 '16 at 05:07
  • More sensible/useful structure of `object` would be `{subject:SUBJECT_NAME, code:SUBJECT_CODE}` – Rayon Jun 10 '16 at 05:12

5 Answers5

11

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);
Rayon
  • 35,420
  • 4
  • 45
  • 69
6

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);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
2

Just loop over each of the keys in the object.

var oldObject = {English: 4, Math: 5, CompSci: 6};
var newArray = [];

// Loop over each key in the object
for (var key in oldObject) {
    // Create a temp object
    var temp = {};
    
    // Set the key of temp
    temp[key] = oldObject[key]

    // Push it to the array
    newArray.push(temp);
}

console.log(newArray)
wot
  • 827
  • 4
  • 10
0

you can directly assign object by {} but you must use [] quote for key value if not that will not worked

 var obj = {English: 4, Math: 5, CompSci: 6};
 var n_obj = [];
 for(var i in obj){
    n_obj.push({[i]:obj[i]});
 }
 console.log(n_obj);
David Jaw Hpan
  • 4,511
  • 3
  • 24
  • 50
-1

You can use JSON.stringify(), String.prototype.match() with RegExp /".*"\:.*(?=,|})/, String.prototype.split() with RegExp /,/, Array.prototype.join() with parameter "},{", JSON.parse()

var obj = {English: 4, Math: 5, CompSci: 6};
var res = JSON.parse("[{" 
          + JSON.stringify(obj)
            .match(/".*"\:.*(?=,|})/g)[0]
            .split(/,/)
            .join("},{") 
          + "}]");
console.log(res);
guest271314
  • 1
  • 12
  • 91
  • 170