Trying to sort a custom JavaScript object

后端 未结 5 1036
时光说笑
时光说笑 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:12

    You are missing the point of creating objects in the first place if you are putting multiple values in a string separated by a delimiter. The structure should instead be,

    cart.attributes = [
        {
            attributes: {
                id: "46913872",
                quantityIterator: 2,
                name: "Dress Color"
            },
            value: "57",
        },
        // repeat for each product
    ];
    

    Making a function to create an object from the encoded string is trivial. Split the string by ':' and record each part separately.

    function makeProduct(key, val) {
        var parts = key.split(':');
    
        var attrs = {};
        attrs.productId = parts[0];
        attrs.quantityIterator = parts[1];
        attrs.name = parts[2];
    
        return { attributes: attrs, value: val};
    }
    

    Example usage:

    makeProduct("46913872:2:Bust", 34); 
    

    returns the object:

    {
        attributes: {
            name: "Bust",
            productId: "46913872",
            quantityIterator: "2"
        },
        value: 34
    }
    

    A generic way to sort an object by multiple fields is listed in this answer.

提交回复
热议问题