javascript - jQuery JSON array conversion -
i trying convert ['peter', 'pan','michael','peter','pan']
[{'peter':2},{'pan':2},{'michael':1}]
counts number of time name appears, print out.
but names[name] = 0;
doesn't work, neither names[name] = names[name] + 1;
var data = ['peter', 'pan','michael','peter','pan']; // create temporary mapping holder. var tmp = {}; (var ii=0; ii < data.length; ii++) { // set key 0 if doesn't exist. if (!(tmp[data[ii]])) { tmp[data[ii]] = 0; } tmp[data[ii]] ++; } // create output array. var output = []; (var key in tmp) { var pobj = {}; pobj[key] = tmp[key]; output.push(pobj); }
you can in single loop, thought might easier understand breaking up.
Comments
Post a Comment