var data = {
a: [
{
count: 0,
str: 'this is a'
}
],
b: [
{
count: 1,
str: 'this is b'
}
]
}
排序后的结果为:
var data = {
b: [
{
count: 1,
str: 'this is b'
}
],
a: [
{
count: 0,
str: 'this is a'
}
]
}
有谁有较简单的方法吗
PHP中文网2017-04-11 09:05:38
首先你这个data根本不是个对象数组...而是个对象
假如是个对象数组的话
function sortNumber(a, b){
return a.count - b.count;
}
data.sort(sortNumber);
PHPz2017-04-11 09:05:38
let nameArr = []
for (let c in con) {
nameArr.push({
name: c,
count: con[c][0].count
})
}
const transform = function (obj) {
let arr = []
for (let item in obj) {
arr.push(obj[item])
}
return arr
}
let objTransArr = transform(con)
for (let d = 0; d < objTransArr.length; d++) {
objTransArr[d].oldIndex = d
}
objTransArr.sort(function (x, y) {
return x[0].count - y[0].count || x[0].oldIndex - y[0].oldIndex
}).reverse()
for (let f = 0; f < objTransArr.length; f++) {
objTransArr[f].oldIndex = f
}
nameArr.sort(function (x, y) {
return x.count - y.count || x.oldIndex - y.oldIndex
}).reverse()
let sourceObj = {}
nameArr.forEach((item, index) => {
sourceObj[item.name] = objTransArr[index]
})