0

I have a json object of the form

{
    "key1": ["value4"],
    "key2": ["value1","value2","value3"],
    "key3": ["value5","value6"]
}

I want to sort them based on the number of the values which should look like

{
    "key2": ["value1","value2","value3"],
    "key3": ["value5","value6"],
    "key1": ["value4"]
}

Anyone please help me.

5
  • That is not valid JSON. Did you mean "key1": ["value4"] etc? Commented Jun 7, 2014 at 8:40
  • oops sorry yes that is "key1":["value4"] Commented Jun 7, 2014 at 8:42
  • Object properties have no language defined order so there is no guarantee as to the order in which you iterate over the properties. Can you explain the use case? Do you want them ordered with ng-repeat? Do you need the keys? Will turning it into an array for easy sorting be acceptable? Commented Jun 7, 2014 at 9:07
  • I want them ordered with ng-repeat Commented Jun 7, 2014 at 9:09
  • Please answer my two other questions :) Commented Jun 7, 2014 at 9:10

2 Answers 2

1

I would recommend creating a new array based on your data and work with that instead:

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>

Demo: http://plnkr.co/edit/WnII9LoQX3oHztXtzoLx?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

Here is my solution, the problem is i cant change the key names but it sorts the values by array's length. So if the key names doesnt matter this would work for you but if you want to sort keys too you need to create a new array.

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  


        } 
    } 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.