Rumah > Soal Jawab > teks badan
var data = [{
"name": "涡阳",
"pinyin": "WoYang"
}, {
"name": "邳州",
"pinyin": "PiZhou"
}, {
"name": "玉溪",
"pinyin": "YuXi"
}, {
"name": "无锡",
"pinyin": "WuXi"
}, {
"name": "萍乡",
"pinyin": "PingXiang"
}];
Kategori mengikut huruf A B C...senarai
seperti
P->
{
"name": "萍乡",
"pinyin": "PingXiang"
},
{
"name": "邳州",
"pinyin": "PiZhou"
}
Huraian pautan yang serupa
Cara mengendalikan set data ini. .
我的代码,比较渣 求更优雅的写法
function jsfu(data) {
var obj={}
data.map(function(item, index) {
let codeIndex = item.pinyin.charAt(0)
if (!obj[codeIndex]) {
obj[codeIndex] = {
item: []
}
}
obj[codeIndex].item.push(item)
})
return obj
}
黄舟2017-05-24 11:38:52
function jsfu(data) {
var map = {}
, arr = []
, dest = []
for (let i = 0; i < data.length; i++) {
arr.push({
code: data[i].pinyin.charAt(0),
item: data[i]
})
}
for (let i = 0; i < arr.length; i++) {
if (!map[arr[i].code]) {
dest.push({
code: arr[i].code,
item: [arr[i].item]
})
map[arr[i].code] = arr[i].code
} else {
for (let j = 0; j < dest.length; j++) {
if (dest[j].code == arr[i].code) {
dest[j].item.push(arr[i].item);
break;
}
}
}
}
//排序
dest.sort(function(a, b) {
if (a.code > b.code) {
return 1;
}
if (a.code < b.code) {
return -1;
}
return 0;
})
return dest
}
jsfu(data)
[
{
"code": "P",
"item": [
{
"name": "邳州",
"pinyin": "PiZhou"
},
{
"name": "萍乡",
"pinyin": "PingXiang"
}
]
},
{
"code": "W",
"item": [
{
"name": "涡阳",
"pinyin": "WoYang"
},
{
"name": "无锡",
"pinyin": "WuXi"
}
]
},
{
"code": "Y",
"item": [
{
"name": "玉溪",
"pinyin": "YuXi"
}
]
}
]
过去多啦不再A梦2017-05-24 11:38:52
data = data.sort(function(a, b) {
return a.pinyin[0].localeCompare(b.pinyin[0])
})
console.log(JSON.stringify(data))