javascript - array object manipulation to create new object -
var actual = [ {"country":"uk","month":"jan","sr":"john p","ac":"24","pr":"2","tr":1240}, {"country":"austria","month":"jan","sr":"brad p","ac":"64","pr":"12","tr":1700}, {"country":"italy","month":"jan","sr":"gim p","ac":"21","pr":"5","tr":900}, {"country":"uk","month":"feb","sr":"john p","ac":"14","pr":"4","tr":540}, {"country":"austria","month":"feb","sr":"brad p","ac":"24","pr":"12","tr":1700}, {"country":"italy","month":"feb","sr":"gim p","ac":"22","pr":"3","tr":600}, {"country":"uk","month":"mar","sr":"john p","ac":"56","pr":"2","tr":1440}, {"country":"austria","month":"mar","sr":"brad p","ac":"24","pr":"12","tr":700}, {"country":"italy","month":"mar","sr":"gim p","ac":"51","pr":"5","tr":200} ]; var expect = [ {month:"jan",val: {"uk":"24","austria":"64","italy":"21"}}, {month:"feb",val: {"uk":"14","austria":"24","italy":"22"}}, {month:"mar",val: {"uk":"56","austria":"24","italy":"51"}} ];
i have array of objects need reshape 1 other work. need manipulation convert 1 function. have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
main factors month, country , "ac" value.
loop through, make object , loop through make array
var actual = [ {"country":"uk","month":"jan","sr":"john p","ac":"24","pr":"2","tr":1240}, {"country":"austria","month":"jan","sr":"brad p","ac":"64","pr":"12","tr":1700}, {"country":"italy","month":"jan","sr":"gim p","ac":"21","pr":"5","tr":900}, {"country":"uk","month":"feb","sr":"john p","ac":"14","pr":"4","tr":540}, {"country":"austria","month":"feb","sr":"brad p","ac":"24","pr":"12","tr":1700}, {"country":"italy","month":"feb","sr":"gim p","ac":"22","pr":"3","tr":600}, {"country":"uk","month":"mar","sr":"john p","ac":"56","pr":"2","tr":1440}, {"country":"austria","month":"mar","sr":"brad p","ac":"24","pr":"12","tr":700}, {"country":"italy","month":"mar","sr":"gim p","ac":"51","pr":"5","tr":200} ]; var outtemp = {}; actual.foreach(function(obj){ //loop through array //see if saw month already, if not create if(!outtemp[obj.month]) outtemp[obj.month] = { month : obj.month, val: {} }; outtemp[obj.month].val[obj.country] = obj.ac; //add country value }); var expected = []; //convert object array format expected (var p in outtemp) { expected.push(outtemp[p]); } console.log(expected);
Comments
Post a Comment