Javascript 如何通过ID获取json数组中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8163859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get data in json array by ID
提问by JaclBlack
I have a problem, may you help me! I have a json array:
我有问题,你能帮我吗!我有一个 json 数组:
"category" : [
{
id: 1,
product: [{id : product_1, type : ball}]
},
{
id : 2,
product :[{id : product_2, type : pen}]
}
]
My problem is: if i have a link such as: http://test/category/1then , How can I do to get product information by category with id = 1 ? Thanks for any suggestion :)
我的问题是:如果我有一个链接,例如:http://test/category/1那么,我该如何按 id = 1 的类别获取产品信息?感谢您的任何建议:)
回答by jfriend00
Assuming your data structure looks like this:
假设您的数据结构如下所示:
var data = {
"category" : [
{
id: 1,
product: [{id : product_1, type : ball}]
},
{
id : 2,
product :[{id : product_2, type : pen}]
}
]
}
Then, you can find the item in the category array with id == 1 by searching through the array like this:
然后,您可以通过像这样搜索数组来在类别数组中找到 id == 1 的项目:
function findId(data, idToLookFor) {
var categoryArray = data.category;
for (var i = 0; i < categoryArray.length; i++) {
if (categoryArray[i].id == idToLookFor) {
return(categoryArray[i].product);
}
}
}
var item = findId(data, 1);
// item.id, item.type
回答by OMA
This is a way to do it in one line and without using for:
这是一种在一行中完成并且不使用 for 的方法:
function filterById(jsonObject, id) {return jsonObject.filter(function(jsonObject) {return (jsonObject['id'] == id);})[0];}
Then if you want to get, for example, the object with id=2, you just use:
然后,如果您想获取 id=2 的对象,则只需使用:
var selectedObject = filterById(yourJson['category'], 2);
And then selectedObject will get this value, as per your example:
然后 selectedObject 将根据您的示例获得此值:
{
id : 2,
product :[{id : product_2, type : pen}]
}
There is a downside: Old browsers, such as IE8, don't support filter() so you need to add this polyfill code for old browser compatibility: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill
有一个缺点:旧浏览器,例如 IE8,不支持 filter(),因此您需要添加此 polyfill 代码以兼容旧浏览器:https: //developer.mozilla.org/en-US/docs/Web/ JavaScript/Reference/Global_Objects/Array/filter#Polyfill
回答by Tadeck
If you save your array of categories in categories
JS variable, you can filter this array based on simple JavaScript (with no jQuery) like that:
如果您将类别数组保存在categories
JS 变量中,您可以基于简单的 JavaScript(没有 jQuery)过滤这个数组,如下所示:
var result = categories.filter(function(element){
if (element.id == 2){
return true;
} else {
return false;
}
});
and then in result[0].product
you will have array of products that are within specific category.
然后result[0].product
您将拥有一系列特定类别的产品。
See this jsfiddlefor a proof.
请参阅此 jsfiddle以获取证明。
PS. filter()
method is not available in all browsers, you may need to apply some code that will make it available if needed and not found. Here is some article on Mozilla Developers Network on the details of filter()
and the code you need to make it work on old browsers: MDN: filter()
.
附注。filter()
方法并非在所有浏览器中都可用,您可能需要应用一些代码以使其在需要时可用但未找到。这是 Mozilla 开发人员网络上的一些文章,详细介绍了filter()
使其在旧浏览器上运行所需的代码:MDN:filter()
。
回答by steveyang
I think the OP wants to retrieve corresponding data from url.
我认为 OP 想要从 url 检索相应的数据。
So the first step is map the url to identifier
所以第一步是将url映射到标识符
var urlParts = window.location.href.split(/\//)
//window.location.href = http://domain.com/category/1
// urlParts = ['http:', '', 'domain.com', 'category', '1']
var id = urlParts.pop();
var category = urlParts.pop();
Then you retrive the data from JSON string with JSON.parse
:
然后你从 JSON 字符串中检索数据JSON.parse
:
var data = JSON.parse('{"category" : [{"id": 1, "product": [{"id" : "product_1", "type" : "ball"}] }, {"id" : 2, "product" :[{"id" : "product_2", "type" : "pen"}] } ]}');
//The data structure
// {"category" : [
// {"id": 1, "product" :
// [
// {"id" : "product_1", "type" : "ball"}
// ]},
// {"id" : 2, "product" :
// [
// {"id" : "product_2", "type" : "pen"}
// ]}
// ]}
At last, you can retrive the data similar @jfriend00's post with id
and category
最后,你可以retrive数据类似@ jfriend00与岗位id
和category
function findId(data, idToLookFor) {
var categoryArray = data.category;
for (var i = 0; i < categoryArray.length; i++) {
if (categoryArray[i].id == idToLookFor) {
return(categoryArray[i].product);
}
}
}
var item = findId(data.category, id);
// item.id, item.type
回答by bazi.the.developer
You might have found the answer, but if you haven't you can simply use the logical OR(||
) operator.
您可能已经找到了答案,但如果没有,您可以简单地使用逻辑OR( ||
) 运算符。
In your case, you can use jQuery's ajax()
method. To grab your product based on id
s just use the below simple logic:
在您的情况下,您可以使用 jQuery 的ajax()
方法。要根据id
s获取您的产品,只需使用以下简单逻辑:
var prodID1 = 1, prodID2 = 2;
if(this.id == prodID || this.id == prodID2) {
//write your JSON data, etc.
//push to array, etc.
}