简体   繁体   English

在Javascript对象中查找特定值

[英]Finding a particular value in a Javascript object

I humbly ask for assistance. 我谦虚地寻求帮助。 I am working on a project where I need to set up a search to find all instances, inside an Object where a particular value equals whatever term the user is searching for. 我正在一个项目中,我需要在该对象中进行搜索以查找所有实例,该对象中的特定值等于用户要搜索的任何术语。 I found the following code: 我发现以下代码:

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

here (to make sure proper credit is given),which works great, but I am looking for some help on expanding the functionality of this code to include the ability to search for more than one element at a time, and also, on the return, display other values in the same objects being returned. 在这里 (确保给予适当的认可),效果很好,但我正在寻求一些帮助,以扩展此代码的功能,使其包括一次搜索多个元素以及返回时的功能。 ,在返回的相同对象中显示其他值。 As an example, the returns, using the above code, are simply [Object]: 例如,使用上面的代码,返回的就是[Object]:

What I was hoping to do was to append the [>Object] with another variable value from the Object, perhaps the ID or Description, both of which are part of the returned results. 我希望做的是在[> Object]后面附加来自Object的另一个变量值,可能是ID或Description,这两个都是返回结果的一部分。 So, the desired results would be something like "Object: ID=b01" or "Object: Desc = This is Maple", something that will allow my users to quickly see which one of the results they need to look at. 因此,所需的结果将是“ Object:ID = b01”或“ Object:Desc = This is Maple”,这将使我的用户快速查看他们需要查看哪个结果。

Thank you in advance for your assistance! 预先感谢您的协助!

From your description, I have changed the function to look through a tree like object and be able to pick out the objects that contain all of the supplied key-value pairs. 根据您的描述,我已更改了该功能,使之可以像对象一样遍历树,并能够挑选出包含所有提供的key-value对的对象。 In addition, it allows you to specify that you want to output extra parameters on the objects that match. 另外,它允许您指定要在匹配的对象上输出额外的参数。 (like the id and description ) (如iddescription

Here is the code and example http://jsfiddle.net/hjhQz/ 这是代码和示例http://jsfiddle.net/hjhQz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM