简体   繁体   English

JSON对象在Javascript中排序

[英]JSON object sort in Javascript

I have a JSON object jobj=JSON.parse(jsnstr) array returned by JSON.parse and I wish to sort it by its name. 我有一个由JSON.parse返回的JSON对象jobj = JSON.parse(jsnstr)数组,我希望按其名称对其进行排序。 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? 但这没有解决,反而我得到未定义的obj任何帮助吗?

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. 您可以做的是设置每个a.name值对数组的引用,然后使用自定义函数对该数组进行排序,就像您在那里一样。

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. 现在,您的refs数组中的所有内容都已排序,您可以通过sorted [index] .object单独访问每个对象。

I think you meant to write this: 我想你打算写这个:

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

You don't need jQuery for this. 您不需要jQuery。 Also, sort modifies the original array. 同样, sort修改原始数组。 So, if jobj is an array, you can just do: 因此,如果jobj是一个数组,则可以执行以下操作:

jobj.sort(sortfunction);

You may also want to account for the case where a.name and b.name are the same: 您可能还需要考虑a.nameb.name相同的情况:

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/ 演示: http : //jsfiddle.net/xmmPL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM