SORU
14 ŞUBAT 2011, PAZARTESİ


jQuery'in kullanın() JSON nesnesi

brnwdrng's question, benzer bir şekilde JSON gibi bir nesne ile arama yapmak için arıyorum.
benim nesnenin yapısı diyelim ki öyle gibi

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."
    }]
};

Kimliği ile nesne=almak istiyorum"".

Bütün eşyaları sıralama gibi çalıştım:

$(TestObj.find(":id='A'"))

ama hiçbir şey iş gibi görünüyor.

Herkes bir madde kullanmadan bazı ölçütlere göre almak bir yol düşünebiliyor 'her'?

CEVAP
14 ŞUBAT 2011, PAZARTESİ


jQuery düz nesne harfleri çalışmıyor. Arama benzer bir şekilde işlev aşağıda 'kimliği (ya da başka bir mal), nesne derinliği ne olursa olsun: . kullanın edebilirsiniz

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

Kullanmak gibi

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • David MeShow

    David MeShow

    10 EKİM 2006
  • GUN-TIME with Brandon

    GUN-TIME wit

    3 ŞUBAT 2009
  • Rootjunky.com

    Rootjunky.co

    22 EKİM 2011