我有一个如下的javascript对象。我必须在AddressTotal下对数据进行排序,仅按以下顺序检查。 1.如果任何元素具有“ Prime”:true,则首先将其放在AddressTotal下。 2.如果没有“ Prime”:true,则对“ Createdate”降序排序。
请注意,关于“ Createdate”格式,可以解决。
var x = {
"accts": [{
"Id": "Acc1",
"Person": true,
"Name": "Hello Roy",
"ExternalID": "123456",
"AddressTotal": [{
"Account": "Acc1",
"Id": "Ad3",
"Name": "1 camac Street",
"City": "Chennai",
"State": "KN",
"Zip": "23451",
"AddType": "office",
"Prime": false,
"RecTypeId": "R3",
"Createdate": "5th Feb 2018"
}, {
"Account_vod__c": "Acc2",
"Id": "Ad2",
"Name": "1 strand Road",
"City": "Mumbai",
"State": "JK",
"Zip": "12345",
"AddType": "College",
"Prime": false,
"RecTypeId": "R2",
"Createdate": "2nd Feb 2018"
}, {
"Account": "Acc1",
"Id": "Ad1",
"Name": "1 Park Street",
"City": "Bangalore",
"State": "TN",
"Zip": "74324",
"AddType": "School",
"Prime": true,
"RecTypeId": "R1",
"Createdate": "1st Feb 2018"
}
],
"Rectype": {
"Name": "ABC",
"Id": "Id1"
}
}
],
"hasAccess": ["A1"]
}
有人可以建议我出路吗?
答案 0 :(得分:0)
这是一个非常标准的sorting problem。
首先测试两个元素的素数,然后比较创建日期的Date
值。
您不能直接比较Createdate
,因为这将导致两个字符串的字母比较,而不是时间戳的数学比较。
var x = {
"accts": [{
"Id": "Acc1",
"Person": true,
"Name": "Hello Roy",
"ExternalID": "123456",
"AddressTotal": [{
"Account": "Acc1",
"Id": "Ad3",
"Name": "1 camac Street",
"City": "Chennai",
"State": "KN",
"Zip": "23451",
"AddType": "office",
"Prime": false,
"RecTypeId": "R3",
"Createdate": "5th Feb 2018"
}, {
"Account_vod__c": "Acc2",
"Id": "Ad2",
"Name": "1 strand Road",
"City": "Mumbai",
"State": "JK",
"Zip": "12345",
"AddType": "College",
"Prime": false,
"RecTypeId": "R2",
"Createdate": "2nd Feb 2018"
}, {
"Account": "Acc1",
"Id": "Ad1",
"Name": "1 Park Street",
"City": "Bangalore",
"State": "TN",
"Zip": "74324",
"AddType": "School",
"Prime": true,
"RecTypeId": "R1",
"Createdate": "1st Feb 2018"
}],
"Rectype": {
"Name": "ABC",
"Id": "Id1"
}
}],
"hasAccess": ["A1"]
};
//TEST
var arr = x.accts[0].AddressTotal.sort(function sorter(a, b) {
if (a.Prime) {
return -1;
}
if (b.Prime) {
return 1;
}
return new Date(a.Createdate).getTime() - new Date(b.Createdate).getTime();
});
console.log(arr);
顺便说一句,accts
是不是一个对象而不仅仅是一个数组的原因吗?