与brnwdrng的问题类似,我正在寻找一种方法来搜索类似JSON的对象,并找到上一个类似键和下一个类似键。假设我的对象的结构如下:
TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Birch",
"description": "Short description of birch."
},
{
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
},
{
"Product": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
},
{
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
},
{
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}],
"id": "B",
"title": "Moderate",
"description": "Short description of category B."
}]};
现在我想找到一个名称为"oak“的标题,在我发现我还想找到"oak”之前的最后一个标题,在本例中是"maple“,下一个标题是”竹子“。
如果有人能为我指出正确的方向,或者给我一个伪代码,我将不胜感激。
谢谢
发布于 2014-04-10 13:30:17
做一些这样的事情
i = 0;
foreach obj in TestObj
if obj.title = Oak,
last_title = TestObj[i].title;
next_title = TestObj[i+2].title;
i++;
endfor发布于 2014-04-10 15:31:28
好的,这是一个快速的代码。
TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Birch",
"description": "Short description of birch."
},
{
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
},
{
"Products": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
},
{
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
},
{
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}],
"id": "B",
"title": "Moderate",
"description": "Short description of category B."
}]
};
var oak, beforeOak, afterOak;
for(var i=0;i<TestObj.Categories.length;i++){
var products = TestObj.Categories[i].Products;
for(var j=0; j< products.length;j++){
var product = products[j];
if(product.name === 'Oak'){
oak = product;
beforeOak = products[j-1];
afterOak = products[j+1];
break;
}
}
if(oak) break;
}
alert("Oak : "+JSON.stringify(oak));
alert("Before Oak : "+JSON.stringify(beforeOak));
alert("After Oak :" + JSON.stringify(afterOak));在这里查看它的实际效果:http://jsfiddle.net/ejDk8/4/
这很容易理解。如果您还不了解JSON,那么JSON是JavaScript的本机对象结构。因此,您可以使用dot表示法访问它。
Starter on JSON in JavaScript
顺便说一下,,你的json有点不一致。第二个类别中数组"Products“的关键字是"Product”,而不是"Products“。所以我擅自改正了它。
https://stackoverflow.com/questions/22979004
复制相似问题