gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:44:22 26 4
gpt4 key购买 nike

我有这个示例数据并将其转换为一组对象,如下所示。这有两个级别: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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com