Skip to content Skip to sidebar Skip to footer

Converting An Object To An Array

I tried by using Object.keys() to convert the object var obj1={ 'jan': { 'COAL': '25' }, 'feb': { 'ROM': '50', 'WASTE': '55' }, 'april'

Solution 1:

This will do:

var res = []
for(i in obj1){
 var rowObj = obj1[i];
 for(j in rowObj){
     var newObj = {'month' : i, 'product' : j, 'quantity' : rowObj[j]}
     res.push(newObj);
 }
}
console.log(res);

Solution 2:

You need to loop over the keys in the outer object, then the keys in the inner objects, so as long as you can depend on ES5 Array methods:

var obj1={
    "jan": {
        "COAL": "25"
    },
    "feb": {
        "ROM": "50",
        "WASTE": "55"
    },
    "april": {
        "COAL": "60"
    }
}

var o = Object.keys(obj1).reduce(function(acc, month, i) {
  Object.keys(obj1[month]).forEach(function(product) {
    acc.push({'month':month, 'product':product, 'quantity':obj1[month][product]})
  });
  return acc;
}, []);

document.write(JSON.stringify(o));

Using ES6 arrow functions it becomes a little more concise:

var o = Object.keys(obj1).reduce((acc, m) => {
  Object.keys(obj1[m]).forEach(p => acc.push({'month':m, 'product':p, 'quantity':obj1[m][p]}));
  return acc;
}, []);

Post a Comment for "Converting An Object To An Array"