如何在javascript中对数组条目进行分组

时间:2015-09-18 06:53:36

标签: javascript html

我有这个示例数据并将其转换为如下所示的对象数组。这有两个级别:Level1和Level2。

var array = [{
  "Level1": "Assigned to",
  "Level2": "Assigned To 1"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 2"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 3"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 1"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 2"
}];

我想用它们的键对它进行分组,下面是密钥的名称/值。 (见下面的样本)。我将如何解决这个问题,以便在我的HTML中实现。

<div id="accordion">
  <h3>Assigned to</h3>
  <div>
    <p>Assigned To 1</p>
    <p>Assigned To 2</p>
    <p>Assigned To 3</p>
  </div>
  <h3>Location</h3>
  <div>
    <p>SubLocation 1</p>
    <p>SubLocation 2</p>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

使用$.each(),您可以迭代数组并获取值,然后操纵它们。

var json = [{
  "Level1": "Assigned to",
  "Level2": "Assigned To 1"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 2"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 3"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 1"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 2"
}];

var LevelArray = []
$.each(json, function(i, val){
  //console.log(val);
  var className =  val.Level1.replace(/\s/g);
  if($.inArray(className, LevelArray) == -1){
    LevelArray.push(className);
    var thisLevel = $('<div>',{
      'class' : className
    });
    thisLevel.append($('<h3>').text(val.Level1));
    var thisRow = $('<div>').append($('<p>').text(val.Level2));
    thisLevel.append(thisRow);
    $('body').append(thisLevel);
  } else {
    var thisLevel = $('.' + className )
    thisLevel.find('div').append($('<p>').text(val.Level2));
  
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>