我有一些格式如下的 JSON 数据:
{
"id": "ABC123",
"offerPrice": 42.00,
"regularPrice": 42.00,
"variations": [{
"key": "Style",
"value": "Black"
}, {
"key": "Personalization",
"value": "2 Lines of Personalization"
}]
}, {
"id": "987ZYX",
"offerPrice": 52.00,
"regularPrice": 52.00,
"variations": [{
"key": "Style",
"value": "Black"
}, {
"key": "Personalization",
"value": "3 Lines of Personalization"
}]
}
我需要做的是查询 'variations' 数组中的值,如果找到匹配则返回对象。
我能够很好地查询“第一级”值:
var results = jQuery.grep(obj, function (element, index) {
return element.offerPrice == "42.00";
});
如果我指定一个索引值(我显然不想这样做),我可以查询变体:
var results = jQuery.grep(obj, function (element, index) {
return element.variations[1].key == "Personalization" && element.variations[1].value == "2 Lines of Personalization";
});
这是我想做的理想情况,但它不起作用:
var results = jQuery.grep(obj.variations, function (element, index) {
return element.key == "Personalization" && element.value == "2 Lines of Personalization";
});
我不断得到:
Uncaught TypeError: Cannot read property 'length' of undefined
这是一个 jsFiddle:http://jsfiddle.net/VzqWW/3/
有什么想法吗?
最佳答案
不存在obj.variations
这样的对象,因为obj 是一个数组。
类似的东西应该可以工作:
var results = jQuery.grep(obj, function (element, index) {
res = jQuery.grep(element.variations, function (element2, index2) {
return element2.key== "Personalization" && element2.value == "2 Lines of Personalization";
});
return (res.length != 0);
});
关于javascript - 查询嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283418/