Skip to content Skip to sidebar Skip to footer

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 an

Solution 1:

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

Solution 2:

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

Solution 3:

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 objectfor (var key in oldObject) {
    // Create a temp objectvar temp = {};
    
    // Set the key of temp
    temp[key] = oldObject[key]

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

console.log(newArray)

Solution 4:

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

Solution 5:

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

Post a Comment for "Convert Javascript Object To Array Of Individual Objects"