假设我有以下JSON文件:
[
{
"id" : "1",
"name" : "Super shirt",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture1"
},
{
"id" : "2",
"name" : "Super duper",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture2"
}
]
等等。如何获得" pic"的价值基于" id"的财产每个对象的属性?那么如果我有一个该对象的id,如何获取每个对象的图片。
答案 0 :(得分:1)
答案 1 :(得分:0)
使用forEach迭代数组
var obj = [
{
"id" : "1",
"name" : "Super shirt",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture1"
},
{
"id" : "2",
"name" : "Super duper",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture2"
}
];
var pic = "";
obj.forEach( function(value){
if (value.id == "1" )
{
pic = value.pic;
}
} );
alert(pic);
答案 2 :(得分:0)
假设您的数据结构如下所示:
var arr= [
{
"id" : "1",
"name" : "Super shirt",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture1"
},
{
"id" : "2",
"name" : "Super duper",
"snippet": "Item description here",
"price" : "some price here",
"category" : "shirt",
"pic" : "picture2"
}
];
然后,您可以通过搜索数组来找到对象中的图片:
function findPicById(data, idToLookFor) {
for (var i = 0; i < data.length; i++) {
if (data[i].id == idToLookFor) {
return(data[i].pic);
}
}
}
例如:
var item = findPicByIdId(data, 1); //return picture1
答案 3 :(得分:0)
var data= [{"id" : "1","name" : "Super shirt","snippet": "Item description here","price" : "some price here","category" : "shirt","pic" : "picture1"},
{"id" : "2","name" : "Super duper","snippet": "Item description here","price" : "some price here","category" : "shirt","pic" : "picture2"}
];
var selected_pic = null;
$.each(data,function(key,value){
if(value.id == "1"){selected_pic = value.pic;}
});
console.log(selected_pic);
尝试以上代码: