Convert object to JSON array?

I am returning the next object. I am calculating 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 names as properties and counts 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'm not sure what is the best approach and the most efficient way to achieve this. Any help is appreciated.

+3


source to share


2 answers


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

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

      



it uses a functional programming style that usually results in cleaner code.

JSBin

+5


source


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

      

+6


source







All Articles