Nice programing

JSON 객체에서 jQuery의 find () 사용

nicepro 2020. 10. 31. 10:08
반응형

JSON 객체에서 jQuery의 find () 사용


brnwdrng의 질문유사하게 JSON과 유사한 객체를 검색하는 방법을 찾고 있습니다.
내 개체의 구조가 다음과 같다고 가정합니다.

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

id = "A"인 개체를 얻고 싶습니다.

나는 다음과 같은 모든 종류의 것들을 시도했습니다.

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

그러나 아무것도 작동하지 않는 것 같습니다.

누구나 'each'를 사용하지 않고 몇 가지 기준에 따라 항목을 검색하는 방법을 생각할 수 있습니까?


jQuery는 일반 객체 리터럴에서 작동하지 않습니다. 아래 함수를 비슷한 방식으로 사용하여 개체의 깊이에 관계없이 모든 'id'(또는 기타 속성)를 검색 할 수 있습니다.

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;
}

다음과 같이 사용하십시오.

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

순수한 자바 스크립트 솔루션이 더 좋지만 jQuery 방식은 jQuery grep 및 / 또는 map 메소드 를 사용하는 것 입니다. 아마도 $ .each를 사용하는 것보다 낫지 않을 것입니다.

jQuery.grep(TestObj, function(obj) {
    return obj.id === "A";
});

또는

jQuery.map(TestObj, function(obj) {
    if(obj.id === "A")
         return obj; // or return obj.name, whatever.
});

Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.

But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.

function getObjects(obj, key, val) {
    var retv = [];

    if(jQuery.isPlainObject(obj))
    {
        if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
            retv.push(obj);

        var objects = jQuery.grep(obj, function(elem) {
            return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
        });

        retv.concat(jQuery.map(objects, function(elem){
            return getObjects(elem, key, val);
        }));
    }

    return retv;
}

Essentially the same as Box9's answer, but using the jQuery utility functions where useful.

········


This works for me on [{"id":"data"},{"id":"data"}]

function getObjects(obj, key, val) 
{
    var newObj = false; 
    $.each(obj, function()
    {
        var testObject = this; 
        $.each(testObject, function(k,v)
        {
            //alert(k);
            if(val == v && k == key)
            {
                newObj = testObject;
            }
        });
    });

    return newObj;
}

For one dimension json you can use this:

function exist (json, modulid) {
    var ret = 0;
    $(json).each(function(index, data){
        if(data.modulId == modulid)
            ret++;
    })
    return ret > 0;
}

You can use JSONPath

Doing something like this:

results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")

Note that JSONPath returns an array of results

(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)


Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'") the way you wanted.

There are jQuery plugins to that effect, like json2xml.

Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.

참고URL : https://stackoverflow.com/questions/4992383/use-jquerys-find-on-json-object

반응형