English 中文(简体)
对JSON对象使用jQuery的find()
原标题:use jQuery s find() on JSON object

Similar to brnwdrng s question, I m looking for a way to search through a JSON-like object.
supposing my object s structure is like so:

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 "))

但似乎什么都不管用。

有人能想出一种方法,在不使用每个标准的情况下,根据某些标准检索项目吗?

最佳回答

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
问题回答

The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/或 map methods. Probably not much better than using $.each

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

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

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

但在本例中,您必须执行一些递归操作,因为数据不是平面数组,而且我们接受任意结构、键和值,就像纯javascript解决方案一样。

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

本质上与Box9的答案相同,但在有用的地方使用jQuery实用程序函数。

········

这适用于[{“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;
}

对于一维json,您可以使用以下方法:

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

您可以使用JSONPath

这样做:

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

请注意JSONPath返回一个结果数组

(顺便说一句,我还没有测试表达式“$..[?(@.id==A)]”。也许需要借助浏览器控制台对其进行微调)





相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签