有一个树形结构,实现一个方法getKeys(data,str),获取字符串str在data中的所有上级节点的名称

有一个树形结构,实现一个方法getKeys(data,str);获取字符串str在data中的所有上级节点的名称,例如:

getKeys(data,'str1') 返回 ‘key1'

getKeys(data,'str3') 返回 ‘key2 key3'

getKeys(data,'str6') 返回 ‘key2 key5 key6'

代码如下:

var data = {
    key1: 'str1',
    key2: {
        key3: 'str3',
        key4: 'str4',
        key5: {
            key6: 'str6'
        }
    }
}
function getKeys(data, val) {
    for (var key in data) {
        if (typeof data[key] === 'object') {
            var t = getKeys(data[key], val)
            return t ? key + ' ' + t : ''
        } else {
            if (data[key] === val)
                return key;
        }
    }
}

console.log(getKeys(data, 'str6'));
原文地址:https://www.cnblogs.com/Qos8/p/11119849.html