I'm pulling data from an XML DB. It's roughly:
<record>
<eventname></eventname>
<company></company>
<city></city>
<state></state>
</record>
I then parse it with the following:
success: function(xml){
$('record',xml).each(function() {
var evname = $(this).find('eventname').text();
var co = $(this).find('company').text();
var city = $(this).find('city').text();
var state = $(this).find('state').text();
...
After I have the variables, I run an each() for the individual states:
$(this).find('state').each(function(){
This way I can return events for each state, and it's working great. What I need to do this year, however, is provide a count of events in each state. For various reasons, the most reliable item is "city". So I tried:
var count = $(this).find('city').length;
But when I parse it with this in the state loop:
$('<div></div>').html('<p>Total: '+ count +'</p>').prependTo('.'+ state);
I get a paragraph line for each city and the resulting number of "1", so:
Total: 1 Total: 1 Total: 1
...
I think that's because AJAX is looping through each record and just returning a single result when it finds it. The count (number of paragraphs) is correct on in each state. If a state has 15 events, there are 15 "Total: 1"s prepended. So the question I have (and I've tried a lot of different methods of parsing), is how do I sum the numbers and get a result like: "Total: 15"?
How about this
success: function (xml) {
var count = 0;
$('record', xml).each(function () {
...
count++;
...
I noticed that find('city')
always returns 1. So increasing count
with 1 in each iteration should work.
We solved it! Turns out I was heading down the wrong path by looking at a sibling, when I needed to just focus on the record.
My colleague wrote a function:
var recordsList = [];
var statesObj = {};
function parser() {
recordsList.forEach(function(record) {
if( !statesObj[record.state] ) {
// If state key doesn't exist, create it
// Each state will have its own key for each indexing, along with a records list
statesObj[record.state] = {
records: [record],
dot_on_map: false
}
}
else {
// If state key exists, Then just add to it.
// The records list in the state key should exist during this iteration
statesObj[record.state].records.push(record);
}
})
//console.log("records:", recordsList);
//console.log("states:", statesObj);
render();
}
function render() {
Object.keys(statesObj).forEach(function(key) {
let state = key;
let stateObj = statesObj[key]; ...
From there, it was just: $('<div></div>').html('<p>Total: '+ stateObj.records.length +'</p>').prependTo('.'+ state);