javascript - How to implement this set of data to be classified and displayed by alphabetical list without changing the data structure
给我你的怀抱
给我你的怀抱 2017-05-24 11:36:52
0
2
489
var data = [{ "name": "涡阳", "pinyin": "WoYang" }, { "name": "邳州", "pinyin": "PiZhou" }, { "name": "玉溪", "pinyin": "YuXi" }, { "name": "无锡", "pinyin": "WuXi" }, { "name": "萍乡", "pinyin": "PingXiang" }];

Sort by letters A B C... list
Such as

P-> { "name": "萍乡", "pinyin": "PingXiang" }, { "name": "邳州", "pinyin": "PiZhou" }

Similar link description

How to operate this set of data. .

我的代码,比较渣 求更优雅的写法 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 }

How to sort, I found that the page is unordered, it is the unordered characteristic of js objects!

给我你的怀抱
给我你的怀抱

reply all (2)
黄舟
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梦
    data = data.sort(function(a, b) { return a.pinyin[0].localeCompare(b.pinyin[0]) }) console.log(JSON.stringify(data))
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!