已经看到有关排序javascript对象的问题,但没有看到如何对对象内的对象进行排序。
我在下面有一个包含多个对象的javascript对象(实际上数据要大得多)。 如何按照last_name中的值按升序或降序对“数据”内的所有内容进行排序,并输出一个新的已排序的“数据”对象?
{"data":[
{"DT_RowId":"row_1","first_name":"Tiger","last_name":"Nixon","age":"61"},
{"DT_RowId":"row_2","first_name":"Garrett","last_name":"Winters","age":"63"},
{"DT_RowId":"row_3","first_name":"Ashton","last_name":"Cox","age":"66"},
{"DT_RowId":"row_4","first_name":"Cedric","last_name":"Kelly","age":"22"},
{"DT_RowId":"row_5","first_name":"Airi","last_name":"Satou","age":"33"}
],"options":[],"files":[]}
答案 0 :(得分:1)
尝试lodash orderBy
_.orderBy(data.data, ['first_name'],['asc']);
答案 1 :(得分:0)
试试这个:
data.data.sort((a, b) => {
if (a.first_name < b.first_name)
return -1
if (a.first_name > b.first_name)
return 1
return 0
})
答案 2 :(得分:0)
您可以使用下面的Array.prototype.sort
: -
o.data.sort(({ last_name: a }, { last_name: b }) => {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
<强>样本强>
let o = {
"data": [{
"DT_RowId": "row_1",
"first_name": "Tiger",
"last_name": "Nixon",
"age": "61"
},
{
"DT_RowId": "row_2",
"first_name": "Garrett",
"last_name": "Winters",
"age": "63"
},
{
"DT_RowId": "row_3",
"first_name": "Ashton",
"last_name": "Cox",
"age": "66"
},
{
"DT_RowId": "row_4",
"first_name": "Cedric",
"last_name": "Kelly",
"age": "22"
},
{
"DT_RowId": "row_5",
"first_name": "Airi",
"last_name": "Satou",
"age": "33"
}
],
"options": [],
"files": []
};
o.data.sort(({ last_name: a }, { last_name: b }) => {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
console.log(o);
&#13;
答案 3 :(得分:0)
您可以使用自定义比较器的数组排序方法。将您的比较逻辑放在函数中。这种排序将在适当的位置进行。 如果您有庞大的数据集,那么我建议您在服务器上执行此操作以加快处理速度。
代码:
<Your data>.data.sort(function(item1,item2){
if (item1.last_name < item2.last_name)
return -1;
if ( item1.last_name > item2.last_name)
return 1;
return 0;
})