根据数组对象中的某个属性值排序
最近做项目,后台返回的数组对象没有排序,而我需要根据序号将数据显示在页面上,但是不想一个一个取值,想到对数组对象排序后然后直接循环显示。数据结构如下:
现在需要升序排列,用sort()方法,
sort()很常用的排序方法,最主要的是里面的比较函数参数,最重要的是定义一个比较函数如下:
function creatCompare(propertyName) { //根据哪个属性值排序
return function (obj1,obj2) {
//对象两两比较
let value1=obj1[propertyName];
let value2=obj2[propertyName];
if(value1<value2){
return -1
}else if(value1>value2){
return 1
}else {
return 0
}
}
}
let familyconsumptions = familyInfoListinfo.familyconsumptions
if (familyconsumptions) {
let sortFamilyconsumptions = familyconsumptions.sort(creatCompare('familyconsumptionId'))
console.log(sortFamilyconsumptions)
for (let i = 0; i < sortFamilyconsumptions.length; i++) {
document.querySelectorAll('.familyconsumptions input')[i].value = sortFamilyconsumptions[i].consumptionData
}
}
let familyincomeinfos = familyInfoListinfo.familyincomeinfos
if (familyincomeinfos) {
let sortFamilyincomeinfos = familyincomeinfos.sort(creatCompare('familyincomeId'))
console.log(sortFamilyincomeinfos);
for (let i = 0; i < sortFamilyincomeinfos.length; i++) {
document.querySelectorAll('.familyincomeinfos input')[i].value = sortFamilyincomeinfos[i].incomeData
}
}
排序后的结果
关于sort的介绍:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
不积跬步无以至千里