作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有这个示例数据并将其转换为一组对象,如下所示。这有两个级别: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>
最佳答案
使用 $.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>
关于javascript - 如何在javascript中对数组条目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645655/
我是一名优秀的程序员,十分优秀!