如何在对象中搜索特定的int或字符串

How to search for a specific int or string within an object?

本文关键字:int 字符串 搜索 对象      更新时间:2023-09-26

我有一个大对象,在不知道它的路径或位置的情况下,我想在对象中找到一个生成的数字。我如何搜索属性,或者只搜索值,甚至搜索布尔?

即具有属性"版本"值为"90"的对象的对象

var objy = {
    example: 'unknown0',
    example1: 'unknown1',
    example2: 'unknown2',
    example3: 'unknown3',
    example4: 'unknown4',
    example5: {
        prop1: 1,
        prop2: 2,
        prop3: 3,
        prop4: 4,
        prop5: {
            etc1: true,
            etc2: false,
            etc4: {
                version: 90
            }
        }
    }
}

http://jsfiddle.net/J5Avu/

如果不知道眼前的"树",这可能吗?

这里有一个函数,它基本上递归地查看对象的属性,寻找propertyName/propertyValue组合,并跟踪"路径"(jsfiddle)。如果未找到,则返回null

function findPropertyAndValueInObject( obj, prop, value, path ) {
    if( obj[prop] === value ) {
        return path;
    }
    else {
        var foundPath = null;
        for( var thisProp in obj ) {
            var propValue = obj[thisProp];
            if( typeof(propValue) === "object" ) {
                foundPath = findPropertyAndValueInObject(propValue, prop, value, path + "." + thisProp);
                if( foundPath !== null ) {
                    break;
                }
            }
        }
        return foundPath;
    }
}
console.log( findPropertyAndValueInObject( objy, "version", 90, "objy" ) );
//prints out "objy.example5.prop5.etc4"

此函数查找给定对象的属性值,在给定字符串路径匹配。在这里,您将发现它与您的数据之间的关系,然后在这里使用wJ库。下面是独立版本。

对于您的使用,object_find('example5.prop5.etc4.version', object);将返回90

/**
 * Find data into an object using string path
 * like : "my.needle.name" into "haystack"
 * @param path
 * @param object object
 * @returns {*}
 */
function object_find(path, object) {
    var base = object, item;
    path = path.split('.');
    while (path.length > 0) {
        item = path.shift();
        if (base.hasOwnProperty(item)) {
            base = base[item];
            if (path.length === 0) {
                return base;
            }
        }
    }
    return false;
}