I have some JSON data in the "data" variable. FORMAT :
{
"0" : {"names":"Pooja, Trivedi"},
"1" : {"names":"Pooja, Rooster"}
}
I need to implement a map so as to count the different names:
Pooja = 2
Trivedi = 1
Rooster = 1
Here is the implementation:
map = new Array();
data = jQuery.parseJSON(data); //convert JSON to object
for (var i = 0; i < data.length; i++) {
var names = data[i].names.split(','); //split the CSVs
for (var j = 0; j < names.length; j++) {
if (map[names[j].trim()] === undefined) {
map[names[j].trim()] = 1;
} else {
map[names[j].trim()]++;
}
}
console.log(map); //shows progressively filled arrays
}
console.log(map); //shows [], an empty array
Inside the loop, the map is updated. However after the end of the i loop, all we have is an empty array. How is this to be resolved?
data.lengthis undefined so it never enters the loop. You can see that on the live demo I linked to.new Map()which stores key/value pairs in the order they are addeddatato be a JSON representation of an array (rather than an object as you currently have), your code does run, but then the lastconsole.logshows the the same as the previous, i.e. not[]as you say in the questionlengthproperty