javascript - How to Group By Json Array -
i have array , want apply group column (key). have this.
app.groupdtdata = function(data, column) { var generateddata=[]; $.each(data,function(i,dt){ // generateddata // if(jquery.inarray( "john", generateddata )) }); }
i have push generateddata
, check jquery.inarray
?
you wouldn't use inarray
need object hold result, not array. use in
operator property in object.
you column value item , check if exist in result. if doesn't exist, add new array name. add item array , lastly return result:
app.groupdtdata = function(data, column) { var generateddata = {}; $.each(data, function(i, dt) { var key = dt[column]; if (!(key in generateddata)) { generateddata[key] = []; } generateddata[key].push(dt); }); return generateddata; };
demo:
function group(data, column) { var generateddata = {}; $.each(data, function(i, dt) { var key = dt[column]; if (!(key in generateddata)) { generateddata[key] = []; } generateddata[key].push(dt); }); return generateddata; } var g = group([ { name: 'john', grp: '1' }, { name: 'elsa', grp: '2' }, { name: 'mandy', grp: '2' }, { name: 'bo', grp: '1' } ], 'grp'); document.write(json.stringify(g));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Comments
Post a Comment