通过比较对象属性来返回对象(不进行排序)

时间:2017-06-28 13:34:41

标签: javascript jquery json asp.net-mvc

我想基于它的两个属性对我拥有的对象进行排序。

我有一个如下对象,

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="402" Width="540"
        xmlns:local="clr-namespace:WpfApplication1">
    <Window.Resources>
        <local:ViewModel x:Key="ViewModel"/> <!--Initialize ViewModel inside XAML-->
    </Window.Resources>
    <Grid Height="367" Width="526" DataContext="{StaticResource ViewModel}">
        <ItemsControl ItemsSource="{Binding Path=MyStrings}" Width="100" BorderBrush="Red">
            <ItemsControl.ItemTemplate> <!--If you want to display your content in a control you can use ItemTemplate as suggested by @mm8-->
                <DataTemplate>
                    <Label Content="{Binding}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <Button Content="Add Label" Height="23" Width="100" Command="{Binding Path=AddStringCommand}"/>
    </Grid>
</Window>

我想根据doc count和geovalue对对象进行排序,即我希望排序的对象先返回doccount值较高的对象,然后返回较低的值。

即。如下所示

    0:Object
        $id:"1"
        MetricValue:8
        GeoValue:"EAST"
        DimensionValue:High
        DocCount:28

    1:Object
        $id:"2"
        MetricValue:20
        GeoValue:"EAST"
        DimensionValue:Medium
        DocCount:28
    2:Object
        $id:"3"
        MetricValue:10
        GeoValue:"West"
        DimensionValue:High
        DocCount:30
    3:Object
        $id:"4"
        MetricValue:20
        GeoValue:"West"
        DimensionValue:Medium
        DocCount:30

以下方法是我正在尝试的方法,但没有成功 这里 0:Object $id:"1" MetricValue:10 GeoValue:"WEST" DimensionValue:High DocCount:30 1:Object $id:"2" MetricValue:20 GeoValue:"WEST" DimensionValue:Medium DocCount:30 2:Object $id:"3" MetricValue:8 GeoValue:"EAST" DimensionValue:High DocCount:28 3:Object $id:"4" MetricValue:20 GeoValue:"EAST" DimensionValue:Medium DocCount:28 是具有我上面提到的对象的对象。

result

有人可以引导我走正确的道路吗?

1 个答案:

答案 0 :(得分:1)

假设您有一个对象数组供您使用.sort()方法:

&#13;
&#13;
var data = [{
  $id:"1",
  MetricValue:8,
  GeoValue:"EAST",
  DimensionValue:"High",
  DocCount:28
},{
  $id:"2",
  MetricValue:20,
  GeoValue:"EAST",
  DimensionValue:"Medium",
  DocCount:28
},{
  $id:"3",
  MetricValue:10,
  GeoValue:"West",
  DimensionValue:"High",
  DocCount:30
},{
  $id:"4",
  MetricValue:20,
  GeoValue:"West",
  DimensionValue:"Medium",
  DocCount:30
}]
console.log("Original: ", data);

data.sort(function(a,b) {
  return (a.DocCount !== b.DocCount) 
    ? (a.DocCount < b.DocCount) 
    : a.GeoValue > b.GeoValue;
})
console.log("Sorted: ", data);
&#13;
&#13;
&#13;