我有一个
形式的json对象{
"key1": ["value4"],
"key2": ["value1","value2","value3"],
"key3": ["value5","value6"]
}
我想根据看起来像
的值的数量对它们进行排序{
"key2": ["value1","value2","value3"],
"key3": ["value5","value6"],
"key1": ["value4"]
}
任何人都可以帮助我。
答案 0 :(得分:1)
我建议根据您的数据创建一个新数组并改为使用它:
var json = {
"key1": ["value4"],
"key2": ["value1", "value2", "value3"],
"key3": ["value5", "value6"]
};
$scope.items = [];
function fillItems() {
for (var key in json) {
if (json.hasOwnProperty(key)) {
$scope.items.push({
key: key,
values: json[key]
});
}
}
}
fillItems();
HTML:
<div ng-repeat="item in items | orderBy:'values.length':true">
Key: {{ item.key }} Values: {{ item.values }}
</div>
答案 1 :(得分:1)
这是我的解决方案,问题是我无法更改键名,但它按数组的长度对值进行排序。因此,如果键名无关紧要,这对您有用,但如果您想对键进行排序,则需要创建一个新数组。
var obj = {
"key1": ["value4"],
"key2": ["value1","value2","value3"],
"key3": ["value5","value6"]
}
//property count of your object
var length = Object.keys(obj).length;
var j;
var flag = true; // set flag to true to begin first pass
var temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < length -1; j++ )
{
if ( obj[Object.keys(obj)[j]].length < obj[Object.keys(obj)[j+1]].length ) // change to > for ascending sort
{
temp = obj[Object.keys(obj)[j]];//swap elements
obj[Object.keys(obj)[j]] = obj[Object.keys(obj)[j+1]];
obj[Object.keys(obj)[j+1]] = temp;
flag = true; //shows a swap occurred
}
}
}