如果"id":"236"
中存在spConfig['attributs'][125]['options']
,则获取。
你将如何在jQuery中执行此操作?
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
答案 0 :(得分:1)
http://api.jquery.com/jQuery.inArray/
if ($.inArray('yourmom', myArray) !== -1) ...
答案 1 :(得分:1)
function findMe(searchTerm, location) {
for ( var i = 0; i < location.length; i++ ) {
if(location[i]['id'] == searchTerm) {
return location[i];
}
}
return null;
}
var searchTerm = '236';
var location = spConfig['attributes']['125']['options'];
var requiredObject = findMe( searchTerm, location );
alert( requiredObject ? requiredObject['label'] : 'Not Found');
答案 2 :(得分:1)
您的数据结构有点复杂,但假设options.id
是唯一的,您可以使用
function foo(arg) {
var filtered;
$.each(spConfig.attributes, function() {
filtered = $(this.options).filter(function() {
return this.id == arg;
});
});
return (filtered.length) ? filtered[0].products : [];
}
传递不存在的键时返回空数组的函数。
此外,如果您有多个attribute
属性(125
除外)并希望迭代它们:
function foo(arg) {
var filtered=[];
$.each(spConfig.attributes, function() {
filtered.push($(this.options).filter(function() {
return this.id == arg;
}));
});
filtered = $(filtered).filter(function() {
return this.length;
});
return (filtered.length) ? filtered[0][0].products : [];
}
或者,如果您始终访问该属性attribute[125]
,您可以将其保留为硬编码以简化:
function foo(arg) {
var filtered = $(spConfig.attributes[125].options).filter(function() {
return this.id == arg;
});
return (filtered.length) ? filtered[0].products : [];
}
如果您需要更多自定义,请传递attribute
属性名称。
function foo(arg, attr) {
var filtered = $(spConfig.attributes[attr].options).filter(function() {
return this.id == arg;
});
return (filtered.length) ? filtered[0].products : [];
}