1

i have a problem and I could not overcome about two days.
I have an delimited string and i want to populate a menu via JQuery.
My array like this;

Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3


and i want to use this menu structure by using JQuery append function (or any other suggested way)
I mean, when the user hover over my menu trigger a menu will pop up and all Countries will be shown and each one has own sub menu elements (Cities).
i would like to point that, how many Countries exist and each Contry has how many cities are unknown.
I used unique function to eleminate duplicated Countries but i cound not put Cities into Countries.
Thanks right now..

4
  • Is your array actually a pipe-delimited string, or a real array? Commented Oct 12, 2011 at 18:20
  • @nrabinowitz i'am sorry it is not array yet :) pipe-delimited string Commented Oct 12, 2011 at 18:28
  • jQuery.unique() doesn't work on arrays of strings or numbers. Commented Oct 12, 2011 at 18:29
  • @mblase75 i've tried to split this string and take Countries as array then i used unique function to delete duplicated countries (i succeed) but i couldn't put cities on countries. Commented Oct 12, 2011 at 18:32

2 Answers 2

2

See this working example: http://jsfiddle.net/nrabinowitz/FDWgF/

You first need to collect the cities for each country in an object with the country names as keys, then iterate through that object to create your list:

var data = "Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3";

// split into country/city pairs
data = data.split('|');

var countries = {},
    pair, country, city;

for (var x=0; x<data.length; x++) {
    // get pair as an array
    pair = data[x].split(',');
    country = pair[0];
    city = pair[1];
    // make sure the country is in our object
    if (!(country in countries)) {
        countries[country] = []
    }
    // add the city to the list for that country
    countries[country].push(city);
}

// now get the values out of the object
$.each(countries, function(country, cities) {
    var $country = $('<li>' + country + '<ul></ul></li>');
    // append each city to sub-list
    $.each(cities, function(i, city) {
        $('ul', $country)
            .append('<li>' + city + '</li>')
    });
    // now append the whole thing to the country list
    $('#countries').append($country);
});
Sign up to request clarification or add additional context in comments.

4 Comments

For what it's worth: jsfiddle.net/mblase75/FDWgF/1 -- same loop, different HTML build. I don't like using $.each when a plain old for loop will do.
Well, I've always been told (mostly by jslint :) that you need to wrap for (x in y) loops with a conditional if (y.hasOwnProperty(x)) statement. This always seems like a pain to me. I also like the scope control the inner function of .each() provides. But it's really just personal preference.
jsfiddle.net/mblase75/FDWgF/2 -- adds some unrequested sorting of countries and cities. Sadly Object.keys isn't universally supported, so an extra array was needed.
@ mblase75, city lists should be warpped be countries' list element but in your fiddle they are self warpped. How can i correct this issue? I mean should be like this <li><a href"#">Country</a><ul><li><a href="#">City</a></li></ul></li>
0

your array should be a multi-dimensional array like this:

var countries = {
"country1":["city1", "city2"],
"country2":["city1"],
"counrty3":["city2", "city2"]
};

Then you will not have duplicate countries, then you should loop through the array with for in and populate the menu that way

var options = "";
foreach(countries as country)
{
    foreach(country as city)
    {
        options += "<option value=" + city+ ">"+ city+ "</options>";
    }
}
$("#cities").html(options)
<select id="cities">
</select>

5 Comments

this is essentially the same solution suggested by nrabinowitz
Except that your object values ought to be arrays, not sub-objects, right?
does it make any practical difference?
Well, for one thing, your code isn't syntactically correct - {city1, city2} is a syntax error in Javascript. It's also usually easier to iterate through an array.
suggestion noted, only thing I would say is he asked for a select box, do you see any problems with the above?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.