使用我的下面的Javascript我将JSON数组定义为变量:
var json = [
{
"pk": 981,
"name": "Uruguay",
"distributor": {
"id": 28,
"name": "Store 1",
"email": "[email protected]",
"phone": "",
"site": "",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
},
{
"pk": 982,
"name": "US Minor Outlying Islands",
"distributor": {
"id": 31,
"name": "International",
"email": "[email protected]",
"phone": "1231231234",
"site": "http://www.example.com",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
},
{
"pk": 983,
"name": "Uzbekistan",
"distributor": {
"id": 31,
"name": "International",
"email": "[email protected]",
"phone": "1231231234",
"site": "http://www.example.com",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
}
];
然后我试图在pk字段上使用jQuery的每个函数和值引用来将name字段值记录到控制台。
$.each(json.pk, function(i, v) {
if (v.pk == 981) {
console.log(v.name);
return;
}
});
我尝试了很多这方面的变化,但我似乎无法触发条件,这将允许我控制日志值。我究竟做错了什么?
你试过这种方式吗?
$.each(json, function(i, v) {
if (v.pk == 980) {
console.log(v.name);
return;
}
});
你需要在json
而不是$each
传递json.pk
var json = [
{
"pk": 981,
"name": "Uruguay",
"distributor": {
"id": 28,
"name": "Store 1",
"email": "[email protected]",
"phone": "",
"site": "",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
},
{
"pk": 982,
"name": "US Minor Outlying Islands",
"distributor": {
"id": 31,
"name": "International",
"email": "[email protected]",
"phone": "1231231234",
"site": "http://www.example.com",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
},
{
"pk": 983,
"name": "Uzbekistan",
"distributor": {
"id": 31,
"name": "International",
"email": "[email protected]",
"phone": "1231231234",
"site": "http://www.example.com",
"ownership": 1,
"shipping_cost": 1600,
"fulfilled": false,
"items": [
213,
215,
217
]
}
}
];
$.each(json, function(i, v) {
if (v.pk == 981) {
console.log(v.name);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
如果JSON
是Array类型,可以很容易地在json
对象中导航。
$.each(json, function (key, value) {
console.log((key + 1), value);
});