如何获取基于另一个属性的 JSON 属性

How to get JSON property based on another property

本文关键字:属性 另一个 JSON 何获取 获取      更新时间:2023-09-26

假设我有一个以下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"
  }
]

等等。如何根据每个对象的"id"属性获取"pic"属性的值?那么如果我有该对象的 id,如何获取每个对象的图片。

你正在寻找Array.find

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

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

用于 each 迭代数组

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

假设您的数据结构如下所示:

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

尝试上面的代码: