0

I have a JSON object jobj=JSON.parse(jsnstr) array returned by JSON.parse and I wish to sort it by its name. I have used

jobj=$(jobj).sort(sortfunction);
 function sortfunction(a,b){  
     return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;  
 };  

But this didnt work out instead i am getting undefined obj any help?

2
  • Your code as-is looks sound, we would need your JSON string to investigate further. Commented Jun 4, 2012 at 17:53
  • 1
    Can you show us what jsnstr looks like? Commented Jun 4, 2012 at 17:56

3 Answers 3

3

You can't sort a hash; it must be an array. What you can do is setup the reference of each a.name value to an array and then sort that array with a custom function like you have up there.

json = JSON.parse(...);
var refs = [];
for(var i in json) {
  var name = i.name;
  refs.push({
    name : name.toLowerCase(),
    object : i
  });
}

var sorted = refs.sort(function(a,b) {
  return a.name > b.name;
});

Now everything in your refs array is sorted and you can access each object individually by sorted[index].object.

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

2 Comments

+1 for "you can't sort a hash". The other answers seem to assume that it's an array. Without seeing the json code, that's a gratuitous assumption.
I didnt work apparently when I looked at the object.The object was a hash some number not the required however previously the object was object. but thanks for telling me the fact that "I cant sort a hash" :)
0

I think you meant to write this:

jobj=$(jobj).sort(function(a,b){  
     return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;  
});

Comments

0

You don't need jQuery for this. Also, sort modifies the original array. So, if jobj is an array, you can just do:

jobj.sort(sortfunction);

You may also want to account for the case where a.name and b.name are the same:

function sortfunction(a,b){  
    var aSort = a.name.toLowerCase(),
        bSort = b.name.toLowerCase();
    if(aSort === bSort) return 0;
    return aSort > bSort ? 1 : -1;  
}

DEMO: http://jsfiddle.net/xmmPL/

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.