按嵌套属性的值对对象属性进行排序

时间:2016-12-29 10:50:18

标签: javascript jquery sorting

我目前正试图根据属性属性的值对对象属性进行排序,如果这有意义的话。

var obj = { 
    1: { name: "Mike", surname: "Smith"},
    2: { name: "Albert", surname: "Einstein"},
    3: { name: "Steve", surname: "Jobs"}
}

假设我想按姓氏对这些属性的顺序进行排序,最终结果是

var obj = { 
    2: { name: "Albert", surname: "Einstein"},
    3: { name: "Steve", surname: "Jobs"},
    1: { name: "Mike", surname: "Smith"}
}

当然,除了将所有姓氏放入一个排序然后重建对象的数组之外,必须有一种优雅的方法。

2 个答案:

答案 0 :(得分:4)

请尝试以下代码:

var arr = [
    {
        f_name: 'George',
        l_name: 'Washington',
        age: 279
    },
    {
        f_name: 'Abraham',
        l_name: 'Lincoln',
        age: 202
    },
    {
        f_name: 'Barack',
        l_name: 'Obama',
        age: 50
    }
];

$(function() {
    $('#headings th').click(function() {
        var id = $(this).attr('id');
        var asc = (!$(this).attr('asc')); // switch the order, true if not set
        
        // set asc="asc" when sorted in ascending order
        $('#headings th').each(function() {
            $(this).removeAttr('asc');
        });
        if (asc) $(this).attr('asc', 'asc');
        
        sortResults(id, asc);
    });
        
    showResults();
});

function sortResults(prop, asc) {
    arr = arr.sort(function(a, b) {
        if (asc) return (a[prop] > b[prop]);
        else return (b[prop] > a[prop]);
    });
    showResults();
}

function showResults () {
    var html = '';
    for (var e in arr) {
        html += '<tr>'
            +'<td>'+arr[e].f_name+'</td>'
            +'<td>'+arr[e].l_name+'</td>'
            +'<td>'+arr[e].age+'</td>'
        +'</tr>';
    }
    $('#results').html(html);
}
table {
    margin: 3px;
}
table th {
    font-weight: bold;
    cursor: pointer;
}
table th, table td {
    padding: 3px;
    border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on the table headings to sort the results.
<table>
    <thead id="headings">
        <tr>
            <th id="f_name">First Name</th>
            <th id="l_name">Last Name</th>
            <th id="age">Age</th>
        </tr>
    </thead>
    <tbody id="results">
        <!-- this will be auto-populated -->
    </tbody>
</table>

答案 1 :(得分:1)

您需要的是一个有订单的对象。这可以是ArrayMap

然后,您需要考虑您的数据模式(即从服务器发出的JSON数据的形状)。我可能会将ID移动到对象本身(替代方法是使其隐式,这很脆弱且容易出错)。

[
  {
    "id": 1,
    "name": "Fred", 
    ...
  }
]

此时它只是一个排序问题。

Arraysort function on the prototype

请注意,如果您需要执行转换为数组,则可以使用Array.from

var obj = { 
  1: { name: "Mike", surname: "Smith" },
  2: { name: "Albert", surname: "Einstein" },
  3: { name: "Steve", surname: "Jobs" },
  length: 4 // largest *zero-based* index 
};

console.log(Array.from(obj));

生成的数组将是稀疏的(有间隙),因此您需要过滤结果以消除它们:

Array.from(obj).filter(populated);

function populated(v) {
  return !!v;
}