Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating grouped lists using array of objects

I have a nested array of objects as follows:

result = [
           [{"country":"France","continent":"Europe","name":"street a"}],
           [{"country":"Brazil","continent":"South America", "name":"street b"},{"country":"Brazil","continent":"South America", "name":"street c"}],
           [{"country":"Germany","continent":"Europe","name":"street d"}]
         ]

Note that this was generated from an array of objects after sorting, using continent and then the country keys.

I want to dynamically generate a list as follows (continent and then countries) and add it to a div:

  1. Europe
    • France
      • street a
    • Germany
      • street d
  2. South America
    • Brazil
      • street b
      • street c

Each time the countries and the continents returned would be different but the result array would be grouped in continent,country order.

Since I am new to HTML, CSS and JavaScript, I am not able to figure out how to dynamically create this list. So far I have managed to generate a unique list of only the continents using :

for(var i=0;i<result.length;i++){
    if($('#continent-list li').filter(function(){
         return $(this).text() == result[i][0].continent;
    }).length == 0){
         $('#continent-list').append('<li>'+result[i][0].continent+'<ul></ul></li>');
}

ie., I iterate through the list and only bother to see the first element [result[i][0]) and add this to an unordered list called 'continent-list'. Each time I also check if the name already exists in the unordered list and if it does not, only then I add.

like image 407
rjn1 Avatar asked Jan 24 '26 11:01

rjn1


1 Answers

I think one way to do this is to loop through the objects in the array and create divs for the continents available while making sure no continent is created more than once then still using the same loop you can use something like

for(i=0;i<=results.length;i++){
  if (result[i].continent == continent) //here talking about the present continent in the main loop{
     //code to create new div for the current country....then same procedure for the street part....
    }
}

Sorry i'm not sounding too jqueryish :D but really i hope you get the scope

like image 64
David Adegoke Avatar answered Jan 27 '26 00:01

David Adegoke