I have a single array json string containing data:
[{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"}, {"Name":"Jack","Age":"95"}]
I have deserialized the data and have successfully written the data to jquery datatables. However i would now like to add a column in the datatable to contain the count of names that are john and names that are jack all in one column. I can get the individual counts by saying the following in a loop:
if (people[i].Name == "John")
{
name_count++;
}
if (people[i].Name == "Jack")
{
name_count2++;
}
How do i get this data to display in One Column that matches either the row containing the name jack or john? I am using C#. Thanks in advance
I would suggest using underscore.js (http://documentcloud.github.com/underscore). You can easily achieve any sort of map/reduce/select you want. Here an example:
var people = [{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"}, {"Name":"Jack","Age":"95"}];
var num_johns = _(people).select(function(obj){
return obj.Name === 'John'}).length;
alert(num_johns); //alerts 2
You can even go a step further and factor out the select function with some currying http://www.dustindiaz.com/javascript-curry/ - depends on what your exact problem is.
You could do some linq grouping against the array
var peeps = from person in people
group person by person.name into bucket
select new { name = bucket.Key, count = bucket.Count() };
This will create an enumerable anonymous type with name and count properties that you can iterate over to get the name and count of the names, eg :
class Guy
{
public int age; public string name;
public Guy( int age, string name ) {
this.age = age;
this.name = name;
}
}
class Program
{
static void Main( string[] args ) {
var GuyArray = new Guy[] {
new Guy(22,"John"),new Guy(25,"John"),new Guy(27,"John"),new Guy(29,"John"),new Guy(12,"Jack"),new Guy(32,"Jack"),new Guy(52,"Jack"),new Guy(100,"Abe")};
var peeps = from f in GuyArray group f by f.name into g select new { name = g.Key, count = g.Count() };
foreach ( var record in peeps ) {
Console.WriteLine( record.name + " : " + record.count );
}
}
}
Will emit:
John : 4
Jack : 3
Abe : 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.