6

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

4
  • 3
    Show us what you've tried, some problems you're facing (specific ones) and we'll gladly help. Commented Jun 10, 2016 at 5: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. Commented Jun 10, 2016 at 5:03
  • 1
    Why do you want to do that? Also, this is pretty much a duplicate of convert object to array of objects. Commented Jun 10, 2016 at 5:07
  • More sensible/useful structure of object would be {subject:SUBJECT_NAME, code:SUBJECT_CODE} Commented Jun 10, 2016 at 5:12

6 Answers 6

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer, just don't like the fact that the asker is asking for someone to spoon-feed them.
Thanks Rayon. Spent 3 hours last night and the best I could do was make nested arrays. Cheers!
7

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);

Comments

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)

Comments

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);

Comments

0

You can turn the object into an array of key-value pairs using Object.entries and then map this array to smaller object created using Object.fromEntries from each individual key-value pair (the key part here is the wrapping in another array before passing to fromEntries):

Object.entries(obj).map(e => Object.fromEntries([e]))

The reverse way is similar: We create a big object using Object.fromEntries, and we pass in an array of key-value pairs. This array is created by flat-mapping (i.e. eliminating on extra layer of arrays) the array of objects to an array of key-value pairs we get from calling Object.entries on each small object. The key here is the flat-mapping, without it we would get an array of arrays of key-value pairs because we added that extra layer in the other conversion to separate the properties.

Object.fromEntries(arr.flatMap(o => Object.entries(o)))

Comments

-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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.