如果数组中的值存在,如何获取数组。 jQuery的

时间:2012-08-03 03:42:04

标签: javascript jquery

如果"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"]
            }]
        }

    }

3 个答案:

答案 0 :(得分:1)

http://api.jquery.com/jQuery.inArray/

if ($.inArray('yourmom', myArray) !== -1) ...

答案 1 :(得分:1)

DEMO

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 : [];
}

Fiddle

传递不存在的键时返回空数组的函数。

此外,如果您有多个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 : [];
}

Fiddle

或者,如果您始终访问该属性attribute[125],您可以将其保留为硬编码以简化:

function foo(arg) {
    var filtered = $(spConfig.attributes[125].options).filter(function() {
        return this.id == arg;
    });
    return (filtered.length) ? filtered[0].products : [];
}

Fiddle

如果您需要更多自定义,请传递attribute属性名称。

function foo(arg, attr) {
    var filtered = $(spConfig.attributes[attr].options).filter(function() {
        return this.id == arg;
    });
    return (filtered.length) ? filtered[0].products : [];
}

Fiddle