我如何通过ID在json数组中获取数据 [英] How can I get data in json array by ID
本文介绍了我如何通过ID在json数组中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,可否帮助我!
我有一个json数组:
I have a problem, may you help me! I have a json array:
"category" : [
{
id: 1,
product: [{id : product_1, type : ball}]
},
{
id : 2,
product :[{id : product_2, type : pen}]
}
]
我的问题是:if i有一个链接,如: http:// test / category / 1 那么,我该如何获取产品信息按类别与ID = 1?
感谢您的任何建议:)
My problem is: if i have a link such as: http://test/category/1 then , How can I do to get product information by category with id = 1 ? Thanks for any suggestion :)
推荐答案
假设您的数据结构如下所示: b
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}]
}
]
}
然后,您可以在类别中找到该项目通过像这样搜索数组来搜索id == 1的数组:
Then, you can find the item in the category array with id == 1 by searching through the array like this:
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
这篇关于我如何通过ID在json数组中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文