It has a tree structure, a method to achieve getKeys (data, str), obtaining the names of all of the upper node in the data of the string str

Has a tree structure, a method to achieve getKeys (data, str); Get the name of all the upper node in the data string str, for example:

getKeys (data, 'str1') returns 'key1'

getKeys (data, 'str3') returns 'key2 key3'

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

code show as below:

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'));

 

Guess you like

Origin www.cnblogs.com/Qos8/p/11119849.html