按名称在js对象中查找属性

时间:2012-12-03 13:58:39

标签: javascript

我有很多结构不一样的物体。但我知道所有人都有属性名称'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'
        },
    }
}

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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"

答案 2 :(得分: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。如果密钥出现多次,则会返回第一个找到的密钥。

相关问题