如何根据另一个属性获取JSON属性

时间:2016-02-15 11:28:27

标签: javascript json

假设我有以下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,如何获取每个对象的图片。

4 个答案:

答案 0 :(得分:1)

您正在寻找Array.find

picture = data.find(x => x.id == SOME_ID).pic

对于旧版浏览器,链接页面上有一个填充。

答案 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);

尝试以上代码: