1

我有很多结构不同的对象。但我知道他们都有属性名称“siteName”。我的问题是如何从这个属性中获得价值。几个对象的解释:

feature1 = {
    display: "name",
    feature: {
        attributes: {
            when: '111',
            what: '222'
        },
        geometry: null
        infoTemplate: undefined
    },
    symbol: null
    siteName: 'aa'
}

feature2 = {
    feature: {
        attributes: {
            when: '111',
            what: '222'
        },
        geometry: null
        infoTemplate: undefined
    },
    static: {
        format: {
            weight: 12,
            siteName: 'cccc'
        },
    }
}
4

3 回答 3

3

这是一个适合您的递归函数。

它返回找到的具有名称的第一个属性的值,否则返回undefined

function findByName(obj, prop) {
    for (var p in obj) {
        if (p === prop) {
            return obj[p];
        } else if (obj[p] && typeof obj[p] === "object") {
            var result = findByName(obj[p], prop);
            if (result !== undefined)
                return result;
        }
    }
}

var result = findByName(myObject, "siteName");

或者这是另一个避免继承属性的变体。

function findByName(obj, prop) {
    if (obj.hasOwnProperty(prop))
        return obj[prop];

    for (var p in obj) {
        if (obj[p] && typeof obj[p] === "object") {
            var result = findByName(obj[p], prop);
            if (result !== undefined)
                return result;
        }
    }
}
于 2012-12-03T14:08:30.073 回答
1

递归循环遍历对象:

function find(obj, name) {
    for (var k in obj) { // Loop through all properties of the object.
        if(k == name){ // If the property is the one you're looking for.
            return obj[k]; // Return it.
        }else if (typeof obj[k] == "object"){ // Else, if the object at [key] is a object,
            var t = find(obj[k], name); // Loop through it.
            if(t){ // If the recursive function did return something.
                return t; // Return it to the higher recursion iteration, or to the first function call.
            }
        }               
    }
}

用法:

find(feature1, "siteName"); //Returns "aa"
于 2012-12-03T14:08:22.320 回答
0

以下功能应满足您的需求:

function getFirstFoundPropertyValue(searchedKey, object) {
    if(typeof object === "object") {
        for (var key in object) {
            var currentValue = object[key];
            if(key === searchedKey) {
                return currentValue;
            }
            var nested = getFirstFoundPropertyValue(searchedKey, currentValue);
            if(typeof nested !== "undefined") {
                return nested;
            }
        }
    }
}

如果找到键,则返回键的值,undefined否则返回。如果键出现多次,将返回第一个找到的键。

于 2012-12-03T14:15:43.670 回答