在网上看到很多关于JS 对象数组的比较排序,但数组中的对象没有嵌套。
下面来一个嵌套的:
var lans = [ { "code": "ENG", "belongs" : [ { "area" : "EU_A", "order" : 3 }, { "area" : "EU_B", "order" : 0 }, { "area" : "EM_A", "order" : 0 }, { "area" : "EM_B", "order" : 0 }, { "area" : "EM_C", "order" : 0 } ] }, { "code": "FRC", "belongs" : [ { "area" : "EU_A", "order" : 2 }, { "area" : "EU_B", "order" : 1 } ] }, { "code": "DEU", "belongs" : [ { "area" : "EU_A", "order" : 1 }, { "area" : "EU_B", "order" : 2 } ] } ]; var value = []; for(var i=0; i<lans.length; i++){ for(var j=0; j<lans[i].belongs.length; j++){ if(lans[i].belongs[j].area === "EU_A"){ value.push(lans[i]); } } } function compare(propL1, sortProp, index){ return function(obj1, obj2){ var belongsA = obj1[propL1]; var belongsB = obj2[propL1]; var value1 = 0, value2 = 0; for(var i=0; i<belongsA.length; i++){ if(belongsA[i].area === index){ value1 = belongsA[i][sortProp]; } } for(var j=0; j<belongsB.length; j++){ if(belongsB[j].area === index){ value2 = belongsB[j][sortProp]; } } return value1 - value2; } } for(var k=0; k<value.length; k++){ console.log("order is: " + value[k].code); } value.sort(compare("belongs", "order", "EU_A")); for(var k=0; k<value.length; k++){ console.log("order after sort is: " + value[k].code); }