imn*_*mns 1 javascript yui yui3
我有一个json数组的对象看起来像这样:{id:'the id', name:'the name'};
我需要循环遍历数组并按名称属性按字母顺序对每个对象进行分组.有没有办法在不使用带有每个字母的switch/if语句的情况下执行此操作?
我不想做的是这样的事情:
if(data[i].name..slice(0, 1) == 'a') {
...
}
Run Code Online (Sandbox Code Playgroud)
它是一个大型数组,其中包含近1,000个对象.我的目标是最终将他们添加到潜水中,所以它看起来像这样:
你可以像这样循环你的集合:
var groupedCollection = {};
for(...){//loop throug collection
var firstLetter = data[i].charAt(0);
if(groupedCollection[firstLetter] == undefined){
groupedCollection[firstLetter] = [];
}
groupedCollection[firstLetter].push(data[i]);
}
//groupedCollection now contait data in the form of {a: [], b:[], etc...}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1391 次 |
最近记录: |