可能会为此投降,但JS对我来说仍然是一个新的野兽。我从db获得了一个数据对象,并希望将它组织在JS数组对象中,如下所示:
[ A: [
{"id": 28, "name": "Ackerman, William"},
{"id": 18, "name": "Anderson, Sherry"},
],
B: [
{"id": 42, "name": "Barry, Tristan"},
{"id": 33, "name": "Baker, Lionel"},
],
C: [
{"id": 79, "name": "Chen, Amy"},
{"id": 21, "name": "Chen, Benjamin"},
{"id": 86, "name": "Cornish, Jezebel"}
]
.....
]
所以我希望唯一键是姓氏的字母,并在组中列出姓氏的人员列表。我只是把孤立的独特字母隔离开来,但是当我把名字列表放在每个键下时我就迷失了。
var list = [];
for(var i=0; i< employees.length; i++) {
var key = employees[i].firstletter;
var obj = {"id": employees[i].employee_id, "name": employees[i].last_name + ', '+ employees[i].first_name};
var name = [];
name.push(obj);
list[key] = name;
}
当然这只给了我每组的最后结果......
答案 0 :(得分:0)
问题是您要为每位员工重新创建name
数组。相反,如果已经为key
(员工初始)创建了一个数组,那么只需重用它即可。如果没有,请创建一个新的:
var list = [];
for(var i=0; i< employees.length; i++) {
var key = employees[i].firstletter;
var obj = {"id": employees[i].employee_id, "name": employees[i].last_name + ', '+ employees[i].first_name};
var name = list[key] || [];
name.push(obj);
list[key] = name;
}
这是有效的,因为undefined
结果(当list[key]
对象不包含list
时,key
获得的结果)是“假的”,所以{{1在这种情况下,将为变量分配一个空数组。
答案 1 :(得分:0)
您可以使用对象进行分组,并使用Array#forEach
迭代数组。
var data = [{ id: 28, firstname: 'William', lastname: 'Ackerman' }, { id: 18, firstname: 'Sherry', lastname: 'Anderson' }, { id: 42, firstname: 'Tristan', lastname: 'Barry' }, { id: 33, firstname: 'Lionel', lastname: 'Baker' }, { id: 79, firstname: 'Amy', lastname: 'Chen' }, { id: 21, firstname: 'Benjamin', lastname: 'Chen' }, { id: 86, firstname: 'Jezebel', lastname: 'Cornish' }],
grouped = Object.create(null);
data.forEach(function (a) {
grouped[a.lastname[0]] = grouped[a.lastname[0]] || [];
grouped[a.lastname[0]].push({ id: a.id, name: [a.lastname, a.firstname].join(', ') });
});
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }