在 JSON 对象上使用 jQuery 的 find()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4992383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:20:36  来源:igfitidea点击:

use jQuery's find() on JSON object

jqueryjquery-selectors

提问by J. Ed

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:

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

I'd like to get an object with id="A".

我想获得一个 id="A" 的对象。

I've tried all sort of stuff such as:

我已经尝试了各种东西,例如:

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

but nothing seems to work.

但似乎没有任何效果。

Can anyone think of a way of retrieving an item based on some criteria without using 'each'?

任何人都可以想出一种根据某些标准检索项目而不使用“每个”的方法吗?

回答by David Tang

jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:

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

Use like so:

像这样使用:

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

回答by davenpcj

The pure javascript solution is better, but a jQuery way would be to use the jQuery grepand/or mapmethods. Probably not much better than using $.each

纯 javascript 解决方案更好,但 jQuery 方法是使用jQuery grep和/或map方法。可能不会比使用 $.each 好多少

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

or

或者

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.

返回匹配对象的数组,或者在 map 的情况下返回查找值的数组。可能只需使用这些就可以做你想做的事。

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.

但是在这个例子中你必须做一些递归,因为数据不是一个平面数组,我们接受任意结构、键和值,就像纯 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;
}

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

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

········

··········

回答by byedissident

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

这对我有用 [{"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;
}

回答by Raugaral

For one dimension json you can use this:

对于一维 json 你可以使用这个:

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

回答by matt

You can use JSONPath

您可以使用JSONPath

Doing something like this:

做这样的事情:

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

Note that JSONPathreturns an array of results

注意JSONPath返回一个结果数组

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

(我还没有测试过表达式 "$..[?(@.id=='A')]" btw。也许它需要在浏览器控制台的帮助下进行微调)

回答by davenpcj

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

我想提到的另一个选项是,您可以将数据转换为 XML,然后jQuery.find(":id='A'")按照您想要的方式使用。

There are jQuery plugins to that effect, like json2xml.

有 jQuery 插件可以达到这种效果,比如json2xml

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

可能不值得转换开销,但这是静态数据的一次性成本,因此它可能有用。