Myoji
Myoji

Reputation: 279

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.

Upvotes: 3

Views: 79

Answers (2)

Manwal
Manwal

Reputation: 23816

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
   }
]

Upvotes: 6

joews
joews

Reputation: 30330

I don't understand how your code example relates to the question, but this turns the data in the first format into the last format:

var output = Object.keys(input).map(function(key) {
  return {
    name: key,
    count: input[key]
  }
});

it uses functional programming style, which usually leads to cleaner code.

JSBin

Upvotes: 5

Related Questions