Trying to sort a custom JavaScript object

后端 未结 5 1049
时光说笑
时光说笑 2021-01-01 04:18

I\'m not too good at JS, but have survived thus far. I\'m creating a sort-of complex JS object and wanting to sort it. The object\'s structure looks like this:

<         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 05:03

    Ok from the comments below I got a clearer picture of what the object is.

    Assuming the object looks like this:

    cart.attributes = {
        '46913872:2:Size' : 10,
        '46913872:2:Hollow-to-Hem' : 57
        // ...
    }
    

    It can't be sorted since it's not an Array. But you can sort it out for printing.

    In plain old javascript you can do:

    // First get all keys:
    var keys = [];
    for (var n in cart.attributes) {
        if (cart.attributes.hasOwnProperty(n)) {
            keys.push(n);
        }
    }
    
    // now sort the keys:
    keys.sort(function(a,b){
        attr_a = a.split(':');
        attr_b = b.split(':');
    
        // sort by product ID:
        if (parseInt(attr_a[0],10) < parseInt(attr_b[0],10)) return -1;
        if (parseInt(attr_a[0],10) > parseInt(attr_b[0],10)) return 1;
        // sort by quantity:
        if (parseInt(attr_a[1],10) < parseInt(attr_b[1],10)) return -1;
        if (parseInt(attr_a[1],10) > parseInt(attr_b[1],10)) return 1;
        // finally sort by name:
        if (attr_a[2] < attr_b[2]) return -1;
        if (attr_a[2] > attr_b[2]) return 1;
        return 0;
    })
    
    // now print out the object in key-sorted-order:
    for (var i=0; i

提交回复
热议问题