用于按类别排列json的jQuery函数

时间:2017-06-16 10:33:46

标签: php jquery json

基于stackoverflow的其他问题,我尝试构建一个函数来查找某个类别的玩家排名。数据来自json文件。

我非常接近,但肯定是错的。控制台上没有错误。

我的代码:

var otfljson = {
 player1: {
    nickname: "Bob",
    min: 100
 },
 player2: {
    nickname: "Amy",
    min: 200
 },
 player3: {
    nickname: "Grant",
    min: 300
 },
 player4: {
    nickname: "Steve",
    min: 200
 },
 player5: {
    nickname: "Joe",
    min: 500
 }
};


$('#result1').html(findrankinjson(otfljson, "player1", "min")); //Wanted: 5
$('#result2').html(findrankinjson(otfljson, "player4", "min")); //Wanted: 3

function findrankinjson(jsonvar, person, rankby) {
    var array = [];
    for (var key in jsonvar) {
        array.push(jsonvar[key]);
    }
    array.sort(function(a, b){
        return b.rankby - a.rankby;
    });
    for (var i = 0; i < array.length; i++) {
        if (i > 0 && array[i].rankby < array[i - 1].rankby) {
            array[i].rank = i+1;
        }
        if (i > 0 && array[i].rankby == array[i - 1].rankby) {
            array[i].rank = array[i-1].rank;
        } 
    }
    return jsonvar[person].rank;
}

该功能的结果是“未定义”。你能救我吗?感谢

1 个答案:

答案 0 :(得分:2)

您的代码的问题是对动态密钥使用.表示法。如果您执行object.rankbyrankby只是可行的,则无效。您需要使用[rankby]表示法。

&#13;
&#13;
var otfljson = {
  player1: {
    nickname: "Bob",
    min: 100
  },
  player2: {
    nickname: "Amy",
    min: 200
  },
  player3: {
    nickname: "Grant",
    min: 300
  },
  player4: {
    nickname: "Steve",
    min: 200
  },
  player5: {
    nickname: "Joe",
    min: 500
  }
};


console.log(findrankinjson(otfljson, "player1", "min")); //Wanted: 5
console.log(findrankinjson(otfljson, "player4", "min")); //Wanted: 3

function findrankinjson(jsonvar, person, rankby) {
  var array = [];
  for (var key in jsonvar) {
    array.push(jsonvar[key]);
  }
  array.sort(function(a, b) {
    return b[rankby] - a[rankby];
  });
  for (var i = 0; i < array.length; i++) {
    if (i > 0 && array[i][rankby] < array[i - 1][rankby]) {
      array[i].rank = i + 1;
    }
    if (i > 0 && array[i][rankby] == array[i - 1][rankby]) {
      array[i].rank = array[i - 1].rank;
    }
  }
  return jsonvar[person].rank;
}
&#13;
&#13;
&#13;