两个具有不同值类型Angularjs的字段。

时间:2022-03-21 07:44:19

I'm trying to order json data based on two fields, and the priority of ordering should be based on field value and then date.

我正在尝试基于两个字段对json数据进行排序,排序的优先级应该基于字段值和日期。

Below is a test demo

下面是一个测试演示

Input json

输入json

[{
"title" : "Title 2",
"pin"   : false,
"date" : 20130411204207
},{
"title" : "Title 3",
"date" : 20140411204207
},{
"title" : "Title 4",
"date" : 20120411204207
},{
"title" : "Title 1",
"pin"   : true,
"date" :  20100411204207
}]

What i'm trying to do is to make object with "pin : true" as first item and then rest of them should be based on descending order of "date", "pin" is an optional field. I was trying "orderBy" method, is there any workaround for this?

我想做的是把“pin: true”作为第一项来制作对象,其余的都应该基于“date”的降序,“pin”是一个可选字段。我正在尝试“orderBy”方法,有什么变通方法吗?

http://jsfiddle.net/tomalex0/tvLUK/1/

http://jsfiddle.net/tomalex0/tvLUK/1/

Output json

json输出

[
{
    "title": "Title 1",
    "pin": true,
    "date": 20100411204207
},
{
    "title": "Title 3",
    "date": 20140411204207
},
{
    "title": "Title 2",
    "pin": false,
    "date": 20130411204207
},
{
    "title": "Title 4",
    "date": 20120411204207
}
]

2 个解决方案

#1


2  

You can get this working by converting the pin into a numeric value as below:

您可以通过将pin转换为数值如下:

$filter('orderBy')($scope.sorted, ["0 + !!pin", "date"], true);

I have updated your fiddle with a working version

我已经更新了你的小提琴与一个工作版本

#2


1  

Try using sort expression like this

尝试使用这样的排序表达式

 $scope.sortData = function (){
    var newdata = $filter('orderBy')(arrayval, ["pin == undefined ? -1 : (pin ? 1 : 0)","date"],true);
     console.log(newdata);
}

#1


2  

You can get this working by converting the pin into a numeric value as below:

您可以通过将pin转换为数值如下:

$filter('orderBy')($scope.sorted, ["0 + !!pin", "date"], true);

I have updated your fiddle with a working version

我已经更新了你的小提琴与一个工作版本

#2


1  

Try using sort expression like this

尝试使用这样的排序表达式

 $scope.sortData = function (){
    var newdata = $filter('orderBy')(arrayval, ["pin == undefined ? -1 : (pin ? 1 : 0)","date"],true);
     console.log(newdata);
}