-1

样本数据:

{
  "data": [
    {
      "name": {
        "full": "JOHN",
        "rank": "SENIOR"
      },
      "mobile": "12345"
    },
    {
      "name": {
        "full": "HENRY",
        "rank": "SENIOR"
      },
      "mobile": "67890"
    },
    {
      "name": {
        "full": "SAM",
        "rank": "JUNIOR"
      },
      "mobile": "54321"
    }
  ]
}

我正在尝试从上面的数据样本中获取高级成员的总数,并且我可以获取data.namedata.mobile,但我无法从父“name”对象中获取“ rank ”数据。谁能指导我获取排名数据。下面是我的javascript:

function countRank(rank) {
    var i;
    for (i in rank.data) {
        if (rank.data[i] == "SENIOR") {
            i++;
        }
        document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
    }
}
<div id="senior"></div>
4

5 回答 5

1

试试这个 JSFIDDLE

 function countRank(rank) {
    var k=0;
    for (var i=0; i< rank.data.length; i++) {
        if (rank.data[i].name.rank == "SENIOR") {
            k++;
        }
        document.getElementById('senior').innerHTML = 'Total senior members: ' + k;
    }
}
countRank(rank);
于 2013-04-12T03:56:42.333 回答
0
function countRank(rank) {
    var count = 0;
    var arr = rank.data;
    for (var i=0; i<arr.length; i++) {
        var name = arr[i].name;
        if (name.rank == "SENIOR") {
            count++;
        }
    }
    alert(count);
}

我检查了它,它运行良好。

于 2013-04-12T04:06:25.760 回答
0

你可以做这样的事情

var rank = {
    "data": [{
        "name": {
            "full": "JOHN",
            "rank": "SENIOR"
        },
        "mobile": "12345"
    }, {
        "name": {
            "full": "HENRY",
            "rank": "SENIOR"
        },
        "mobile": "67890"
    }, {
        "name": {
            "full": "SAM",
            "rank": "JUNIOR"
        },
        "mobile": "54321"
    }]
};

function countRank(rank) {
    var i = 0,
        arr = rank.data;
    for (var j = 0; j < arr.length; j++) {
        for (var prop in arr[j]) {
            if (arr[j][prop].rank == "SENIOR") {
                i++;
            }
            document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
        }
    }
}

countRank(rank);
于 2013-04-12T04:09:55.380 回答
0

使用 jQuery,您可以轻松地从上述数据中找到排名。jsFiddle 上的结帐示例

http://jsfiddle.net/uBnfu/

$.each(jsonData.data, function (index, value) {
                    alert(value.name['rank']);
                });
于 2013-04-12T04:11:26.120 回答
0
myObject.data[0].name.rank
>>> "SENIOR"

假设整个对象被称为obj

var i=0;
for (i=0; i < obj.data.length; i++) {
    console.log(obj.data[i].name.rank);
}
于 2013-04-12T03:57:58.900 回答