【问题标题】:Group array by name in Jquery and display as list在 Jquery 中按名称对数组进行分组并显示为列表
【发布时间】:2017-10-13 12:06:45
【问题描述】:

我有一个这样的数组:

{
"data": [
{
  "cityname": "Newyork",
  "countryname": "USA"
},
{
  "cityname": "amsterdam",
  "countryname": "Netherland"
},{
  "cityname": "Washington",
  "countryname": "USA"
},{
  "cityname": "London",
  "countryname": "UK"
},{
  "cityname": "Los Angeles",
  "countryname": "USA"
},{
  "cityname": "Assen",
  "countryname": "Netherland"
},
,{
  "cityname": "Liverpool",
  "countryname": "UK"
},
,{
  "cityname": "chicago",
  "countryname": "USA"
},
{
  "cityname": "New Delhi",
  "countryname": "India"
},
]
}

我的目标是列出对应国家下的所有城市。在这个数组中,有相同的国家名称。我想在 jquery 中按国家/地区名称对这个数组进行分组。并想列出这样的国家和城市。

<label>USA</label>
<ul>
<li>Newyork</li>
<li>Washington</li>
<li>Chikago</li>
<li>Los Angeles</li>
</ul>

<label>UK</label>
<ul>
<li>London</li>
<li>Liverpool</li>
</ul>

<label>Netherland</label>
<ul>
<li>Amsterdam</li>
<li>Assen</li>
</ul>

<label>India</label>
<ul>
<li>New Delhi</li>
</ul>

那么如何在不使用任何插件的情况下在 jquery 中以更好的方式做到这一点?请帮忙。谢谢。

【问题讨论】:

  • 为什么首先需要或想要 JQuery 进行数组操作?
  • Stackoverflow 不是免费的代码编写或教程服务。目的是让您展示您尝试过的内容,并让人们帮助修复您的代码

标签: javascript jquery html arrays grouping


【解决方案1】:

这可以通过一些类似这样的逻辑来实现

$(data).each(function(){
if($('#'+this.countryname).length)
{
  $('#'+this.countryname).append('<li>'+this.cityname+'</li>')
}
else
 {
$('#bodyDiv').append('<label>'+this.countryname+'</label><ul id="'+this.countryname+'"></ul>')
$('#'+this.countryname).append('<li>'+this.cityname+'</li>')
}
})

这里的#bodyDiv 是您要填充的 div 元素的 id ...

【讨论】:

    【解决方案2】:

    这是我的解决方案,你可以see in action on JSFiddle here

    data.forEach(function(datum) {
      let countryList = $('[data-countryname='+datum.countryname+']');
      if(countryList.length === 0) {
        let newLabel = document.createElement('label');
        let newList = document.createElement('ul');
        $(newLabel).html(datum.countryname);
        $(newList).attr('data-countryname',datum.countryname);
        $('body').append(newLabel);
        $('body').append(newList);
        countryList = newList;
      }
      let newListItem = document.createElement('li');
      $(newListItem).html(datum.cityname);
      countryList.append(newListItem);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      相关资源
      最近更新 更多