【发布时间】:2021-03-13 15:37:31
【问题描述】:
我正在尝试采用单个教派数组并将项目分组到一个多教派数组中。
这就是我所做的
$(function(){
// this array should be groupped by group value "if one exists." In this case, it should be 2 groups
// (group_1 and group_2)
var items = [
{
group: "group_1",
text: "Text 1",
value: "1",
},
{
group: "group_2",
text: "Text 1",
value: "21",
},
{
group: "group_1",
text: "Text 2",
value: "2",
},
{
group: "group_1",
text: "Text 3",
value: "3",
},
{
text: "Text 30",
value: "30",
}
];
var groups = [];
$.each(items, function(i, item){
if( typeof item.group === 'undefined'){
return; // continue, ignore any item that does not have a group name
}
if( !(item.group in groups)) {
// create a new group in the array
groups[item.group] = [];
}
// push item to the group
groups[item.group].push({text: item.text, value: item.value});
});
$('#console').text('Expecting the length to be 2 groups but getting ' + groups.length);
console.log(groups);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console">
</div>
我预计 groups 数组的长度为 2,因为有 group_1 和 group_2。但是,我得到长度为 0 的数组。
如何按group 属性的值正确分组这些项目?
【问题讨论】:
-
您当前尝试的主要问题是您使用数组 (
groups = []) 而使用"group_1"访问每个组。这些不是索引,而是键。使用对象可以解决大部分问题。这意味着将groups = []替换为groups = {}。 (请记住,对象没有length属性。)
标签: javascript jquery arrays