Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to JSON Array?

I have the following object being returned. I am counting a list of names by reading from a json file and storing the results in a new object.

{
    ted: 501,
    jeff: 40,
    tony: 90
}

The following function creates an object with the names as properties and the count as their values.

function countNames(json){

    var count = {};

    for (var i = 0, j = json.length; i < j; i++) {

       if (count[json[i].name]) {
          count[json[i].name]++;
       }
       else {
          count[json[i].name] = 1;
       } 
    }  

    return count;
}

I need to create an array of objects that generate a result like this.

[
    {
        name: 'ted',
        total: 501
    },
    {
        name: 'jeff',
        total: 40
    }
    {
        name: 'tony',
        total: 90
    }           
]

I am not sure what the best approach and most efficient way of achieving this is. Any help is appreciated.

like image 753
Myoji Avatar asked Sep 06 '26 14:09

Myoji


1 Answers

Consider this following Javascript snippet:

for (var item in obj) {
    result.push({
        name: item,
        total: obj[item]
    });
}

Working DEMO

Output:

[  
   {  
      "name":"ted",
      "total":501
   },
   {  
      "name":"jeff",
      "total":40
   },
   {  
      "name":"tony",
      "total":90
   }
]
like image 186
Manwal Avatar answered Sep 08 '26 03:09

Manwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!