3

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.

2
  • 4
    What's city? Can't you already take what you've done with countNames and just add each to an array instead? Commented May 1, 2015 at 12:59
  • Sorry, it should have been the name property. I corrected. Commented May 1, 2015 at 13:03

2 Answers 2

6

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
   }
]
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution better because it doesn't require ECMA 5.1, yet the performance appears to be nearly the same as using the Object.keys() method. I think the for-in look is ECMA 3 or earlier (?).
5

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

2 Comments

Note to OP: Keep in mind Object.Keys() is ECMA 5.1, so <IE9 will throw up on you. (Though I suppose for...in has the same limitation) :: Also, @joews: SO has code snippets now, no need to reference an off-site JSBin.
@BradChristie Thanks for the compatibility note. I prefer JSBin where there is no visual output, or when I think the OP may want to play about with the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.