在JavaScript排序深对象 [英] sort deep object in javascript
本文介绍了在JavaScript排序深对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是排序的最佳方式是:
What is the best way to sort this:
{
abc: {
string: 'lorem',
date: 2
},
enc: {
string: 'ipsum',
date: 1
}
}
这个:
[{
id: 'enc',
string: 'ipsum',
date: 1
},
{
id: 'abc',
string: 'lorem',
date: 2
}]
我需要一个平面物体的日期(数字)进行排序的数组。
I need an array sorted by the date (Number) with a flat object.
推荐答案
首先,您需要将原来的对象转换格式你想要一个数组:
First, you need to convert the original object into an array in the format you want:
var arr = [];
for (var key in obj)
if (obj.hasOwnProperty(key)) {
var o = obj[key];
arr.push({ id: key, string: o.string, date: o.date });
}
然后,您可以使用数组排序
方法使用自定义比较由日期字段排序:
Then, you can use the array sort
method with a custom comparator for sorting by the date field:
arr.sort(function(obj1, obj2) {
return obj1.date - obj2.date;
});
这篇关于在JavaScript排序深对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文