Skip to content

Instantly share code, notes, and snippets.

@cdiaz
Last active September 8, 2016 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdiaz/66fd530f6d935da782fff11057ce2d2e to your computer and use it in GitHub Desktop.
Save cdiaz/66fd530f6d935da782fff11057ce2d2e to your computer and use it in GitHub Desktop.
Json Object Group by column
function sortOn( data, attribute ) {
data.sort(
function( a, b ) {
if ( a[ attribute ] <= b[ attribute ] ) {
return( -1 );
}
return( 1 );
}
);
}
function groupBy(attribute, data, row_name) {
var groups = [];
var groupValue;
sortOn(data, attribute);
for ( var i = 0 ; i < data.length ; i++ ) {
var object = data[ i ];
if ( object[ attribute ] !== groupValue ) {
var group = {
[attribute]: object[attribute],
[row_name]: []
};
groupValue = group[attribute];
groups.push( group );
}
group[row_name].push( object )
}
return(JSON.stringify(groups));
}
var data = [{"transaccion_id":1,"fecha":"2016-08-08T05:00:00.000Z","valor":"46000","categoria":"Gastos Administrativos","detalle":"Arrendamiento Local (Junio - Agosto)","tipo":"egreso"},{"transaccion_id":2,"fecha":"2016-04-27T05:00:00.000Z","valor":"5000","categoria":"Contribuciones y afiliaciones","detalle":"Afiliación","tipo":"ingreso"},{"transaccion_id":3,"fecha":"2016-07-17T05:00:00.000Z","valor":"1100000","categoria":"Abonos","detalle":"Abono","tipo":"ingreso"},{"transaccion_id":4,"fecha":"2016-08-07T05:00:00.000Z","valor":"255000","categoria":"Abonos","detalle":"Abono (dia asamblea)","tipo":"ingreso"},{"transaccion_id":5,"fecha":"2016-08-07T05:00:00.000Z","valor":"10000","categoria":"Abonos","detalle":"Abono ","tipo":"ingreso"},{"transaccion_id":6,"fecha":"2016-08-23T05:00:00.000Z","valor":"20000","categoria":"Comisiones","detalle":"Pago comision ventas","tipo":"egreso"}]
console.log(groupBy('fecha', data, 'movimientos'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment