如何按相同的值对JSON数据进行排序?

问题描述 投票:0回答:3

我有JSON数据,看起来像这样:

{
"items":[
{"name":"Dondasch",
"tier":"Rare"
},
{"name":"Elight",
"tier":"Rare"
},
{"name":"Krak",
"tier":"Unique"
}
]
}

我正在寻找一种通过“Tier:???”对它们进行排序的方法。我想将具有相同值的所有“项目”组合在一起,最好是以我定义的方式(如果,我可以选择具有“稀有”或“唯一”的那些首先出现,而不是按字母顺序排列。已经对它们进行了排序,我需要能够在它们上执行此代码:

data.items.forEach(wynnitem => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

      const h1 = document.createElement('h1');
      $(h1).hide();
      h1.textContent = wynnitem.name;
      if (wynnitem.tier == "Unique") {
        h1.setAttribute('class', 'unique');
      } else if (wynnitem.tier == "Rare") {
        h1.setAttribute('class', 'rare');
      } else if (wynnitem.tier == "Legendary") {
        h1.setAttribute('class', 'legendary');
      } else if (wynnitem.tier == "Mythic") {
        h1.setAttribute('class', 'mythic');
      }
      $(h1).fadeIn(1000);
}):

我发现的任何其他问题都只是按字母顺序排序,而不是按某个值排序。

javascript json
3个回答
0
投票

你可以将Array.prototype.sort方法应用于项目并给它一个compareFn

items.sort(function(a, b) {
    if (a.tier < b.tier) {
        return -1;
    }

    if (a.tier > b.tier) {
        return 1;
    }

    return 0;
});

0
投票

试试这个 :

  var list = {
    "items":[
    {"name":"Dondasch",
    "tier":"Rare"
    },
    {"name":"Elight",
    "tier":"Rare"
    },
    {"name":"Krak",
    "tier":"Unique"
    }
    ]
    }

然后使用排序数据

list.items.sort(function(a, b) { return a["tier"]-b["tier"]} || a["name"] - b["name"]);

0
投票

您只需要定义排名/优先级表并按此条件排序:

const orderRanks = {
  unique: 2,
  rare: 4,
  legendary: 42,
  mythic: 420
};

const items = /*your items array*/;
items.sort((lhsItem, rhsItem) => {
  const lhs = lhsItem.tier.toLowerCase();
  const rhs = rhsItem.tier.toLowerCase();
  return orderRanks[lhs] - orderRanks[rhs];
  /*
  == -> 0
  lhs < rhs -> negative
  lhs > rhs -> positive

  this works because it is simple numbers (not NaN nor limits)
  */
});
© www.soinside.com 2019 - 2024. All rights reserved.