How to sort a Javascript object, or convert it to an array?

前端 未结 7 587
囚心锁ツ
囚心锁ツ 2020-12-13 04:13

I have some JSON data that I get from a server. In my JavaScript, I want to do some sorting on it. I think the sort() function will do what I want.

However, it seems

7条回答
  •  醉话见心
    2020-12-13 04:31

    jQuery offers a map function, which will iterate through each element in an array or object and map the results into a new array.

    Prior to jQuery 1.6, $.map() supported traversing arrays only.

    We can use this to convert any object to an array as follows...

      myArray = $.map(myObject, function (el) {
        return el;
      });
    

    But... if the callback function returns null or undefined, then that value is removed from the array, in most cases this is useful, but it can cause problems if you need null values in myArray.

    jQuery offers a solution for this... return the value as an array with the single value

    myArrayWithNulls = jQuery.map(myObject, function (el) {
      return [el];
    });
    

    Here's a fiddle demonstrating the two approaches: http://jsfiddle.net/chim/nFyPE/

    http://jsperf.com/object-to-array-jquery-2

提交回复
热议问题