我有一些格式如下的 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/
有任何想法吗?