Trying to sort a custom JavaScript object

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

    First of all, it's really hard to understand the structure of the object. Is this what it looks like?

    [
      {  "46913872:2:Size" : 10 },
      {  "46913872:2:Hollow-to-Hem": 57},
      {  "46913872:1:Hips" : "34"}, ...
    ]
    

    It looks like you want it to sort to

    [
      {  "46913872:1:Hips" : "34"}, // all ids are the same here, but this index is 1
      {  "46913872:2:Hollow-to-Hem": 57}, // index is 2 but Hollow comes before Size
      {  "46913872:2:Size" : 10 },
    ]
    

    The following solution works if I understood your object structure. Like ThatSteveGuy said, you can pass a comparator to your sort method. Since the object is so complicated, this is what you would do

    attributes.sort(function(a, b){
      // Make sense of your objects a and b. See the inner function defined below
      var newA = improveObject(a);
      var newB = improveObject(b);
    
      if (newA.id > newB.id) { return 1; }
      if (newA.id < newB.id) { return -1; }
      // id is the same, check index
      if (newA.index > newB.index) { return 1; }
      if (newA.index < newB.index) { return -1; }
      // index is the same, check name
      if (newA.name > newB.name) { return 1; }
      if (newA.name < newB.name) { return -1; }
      // it's the same thing 
      return 0;
    
      // Turns {  "46913872:2:Size" : 10 }
      // into {id: 46913872, index: 2, name: "Size", value: 10}
      function improveObject(obj) {
        for (var key in obj) {
          var pieces = key.split(":");
          return {
            id: parseInt(pieces[0]),
            index: parseInt(pieces[1]),
            name: pieces[2],
            value: obj[key];
          };
        }
      }
    });
    

    However, the object really doesn't make sense. I would urge you to re-think its structure. Even if I didn't fully understand your object (you should have listed the actual json for the object), the example tells you all you need to know about sorting in js.

提交回复
热议问题