1 回答
TA贡献1815条经验 获得超10个赞
您不能将sort()函数用于对象。为了使您的代码工作,您应该转换this.calculated为数组。
您可以使用此代码片段将对象转换为数组。
let calculated = {
"object1": {
"selected": false,
"value": 1
},
"object2": {
"selected": false,
"value": 20
},
"object3": {
"selected": false,
"value": 4
},
"object4": {
"selected": false,
"value": 24
},
"object5": {
"selected": false,
"value": 6
},
"object6": {
"selected": false,
"value": 0.26
},
"object7": {
"selected": true,
"value": 1.52
},
"object8": {
"selected": false,
"value": 0.54
},
"object9": {
"selected": false,
"value": 4.27
}
}
let calculatedArray = []
for (const [key, value] of Object.entries(calculated)) {
calculatedArray.push({
id: key,
...value
})
}
sortedData = function() {
if(calculatedArray) {
return calculatedArray.sort(function(a, b) {
return b.selected - a.selected
})
} else {
return []
}
}
console.log(sortedData())
console.log(calculatedArray)
添加回答
举报