Sorting a JSON Object

Problem trying to sort a JSON object. Basically, people can add products in any random order to our order form, but the order that it shows in the summary should be the way we want them to be positioned (and not the order they choose), so therefore I need to sort by 'id' (or we will sort the "pos" field later)

Essentially, I need to sort by id in ascending order. 1,2,103 instead of 2,103,1

I seem to have problems, because the index into individual objects is numbers (or just that they are there ...).

I need to do something line by line array.sort (function (a, b) {return a.id-b.id}); but I assume that this does not work, because 1, its not an array (its object) and 2, it has these annoying indexes (which I need for another part of my code) ...

Any ideas ????

var products = {
    "2": {
        "id": "2",
        "price": "119",
        "quantity": "1",
        "thumb": "img\/store\/comp-08n.png"
    },
    "103": {
        "id": "103",
        "price": "109",
        "quantity": "1",
        "thumb": "img\/store\/basketballhoop.png"
    },
    "1": {
        "id": "1",
        "price": "309",
        "quantity": "1",
        "thumb": "img\/store\/comp-08.png"
    }
};
+5
source share
5 answers

How many items do you need in your orders? You can safely sort 10,000 items in a Javascript array without much speed issues. Why don't you work with a real array?

You can even add custom properties to it, something like

var products = [...];

products.findById = function(id) {
   for (var i=0, len=this.length; i<len; i++) {
      if (id == this[i].id) return this[i];
   }
   return null;
};

alert( products.findById(103).price );   // -> 119

and add predefined sorters like

products.sortById = function() {
    this.sort(function(a,b) {
        return a.id - b.id;
    });
};

products.sortById();   // sort array by product id

** EDIT **

PHP - :

$products = array(
    2 => array( 'id' => 2, ... ),
    103 => array( 'id' => 103, ... ),
    1 => array( 'id' => 1, ... ),
);

// get a JSON array
$jsonArray = json_encode(array_values($products));

, .

** **

. push,

products.push({id:123, price:200.49, quantity:1, thumb:'/path/to/file'});

, , - :

products.removeById = function(id) {
   for (var i=0, len=this.length; i<len; i++) {
      if (id == this[i].id) return this.splice(i, 1)[0];
   }
   return null;
};

products.removeById(123);    // -> returns the removed element! or null if nothing was removed

( Chrome ).

+5

JavaScript JSON:

  • key/value map (object) -
  • - / map () - .

. .

+4

, , javascript

var alphabetizeJSON = function(obj){
    var key,
        array = [],
        stringifiedValuesObj = {},
        jsonKeyVal = "",
        i,
        keyName;

    for (key in obj) {
        if (typeof obj[key] === "object"){
            stringifiedValuesObj[key] = "" + alphabetizeJSON(obj[key]);
        } else {
            obj[key] = obj[key].replace(/\"/gi,'\\\"');
        }
        array.push(key);
    }

    array.sort();

    for (i = 0; i < array.length; i++){
        keyName = array[i];
        jsonKeyVal += '"' + keyName + '": ';
        jsonKeyVal += stringifiedValuesObj[keyName] ? stringifiedValuesObj[keyName] : '"' + obj[keyName] + '"';
        if (i < array.length - 1 ) {
            jsonKeyVal += ',';
        }
    }

    return '{ ' + jsonKeyVal + '}';
};
+2

JSONArray s. , . http://json.org/java/

0

In fact, you should be able to use an array instead of an object for this task, and this will solve many of your difficulties.

If you cannot do this, you can convert the object to an array to arrange it ... something like this:

var a = []
for (var p in obj) {
  a[+p] = obj[p]
}

If you cannot do this, you can dynamically add information to the page in the order you want (below is a bad idea) ...

for (var i = 0; i < 10000; i++) {
  if (obj[i] !== undefined) {
    add_to_page(obj[i])  //define this somewhere
  }
}
0
source

All Articles