一道前端面试题

题目描述

有一个树形结构:

var data = {
  key1: 'str1',
  key2: {
    key3: 'str3',
    key4: 'str4',
    key5: {
      key6: 'str6'
    },
    key8: {
      key9: 'str9'
    }
  },
  key7:"str7"
  // ...
}

实现一个方法getKeys(data, str),获取字符串 str 在 data 中所有的上级节点名称,例如:
getKeys(data, 'str1') 返回 'key1'
getKeys(data, 'str3') 返回 'key2 key3'
getKeys(data, 'str6') 返回 'key2 key5 key6'

阅读 3.7k
9 个回答
function  getKeys(data,str){
    var result=[];
    function recursion(data,str){
        for(var key in data){
            if(data[key] == str){
                result.push(key);
                return result;
            }
            if(typeof data[key] == 'object'){
                result.push(key);
                return recursion(data[key],str)
            }
        }
    }
    recursion(data,str);
    return result.join(' ');
}
var result =[]
const GetKey = (data,key) =>{
    for(let v in data){
        if(data[v] == key){
            result.push(v)
            return result
        }
        if(typeof data[v] == 'object'){
            result.push(v)
            return GetKey(data[v],key)
        }
    }
}
 function getKeys(data, value) {
    const walker = (data, value, paths = []) => {
      const keys = Object.keys(data);
      let i = 0;

      for (i = 0; i < keys.length; i++) {
        let key = keys[i];
        let item = data[key];

        if (item === value) {
          paths.push(key);
          return true;
        }

        if (typeof item === 'object') {
          paths.push(key);

          let flag = walker(item, value, paths);

          if (!flag) {
            paths.pop();
          } else {
            return true;
          }
        }
      }

      return false;
    };

    const paths = [];

    let finded = walker(data, value, paths);

    return finded ? paths : [];
  }

自问自答:

function getKeys(data, str) {
  for(let key in data) {
    if(typeof data[key] == 'string' && data[key] == str) {
      this.keyName ? this.keyName += key: this.keyName = key
      return this.keyName
    } else if(typeof data[key] == 'object') {
      this.keyName ? this.keyName += key: this.keyName = key
      this.keyName += ' '
      return getKeys(data[key], str)
    }
  }
}

getKeys.prototype.keyName = ''

console.info(getKeys(data, 'str6'))

今天突然想到的方法,之前我想的是用正则,但是这个正则规则想起来比较蛋疼,但肯定是可行的,就没回答,这次想到的是通过indexOf来做:

function getKeys(data, val) {
  let keyStr = ''
  eachObj(data, val)
  function eachObj(data, val) {
    for (let key in data) {
      if (JSON.stringify(data[key]).indexOf(val) > -1) {
        keyStr += (key + ' ')
        if (typeof data[key] != 'string') {
          eachObj(data[key], val)
        }
      }
    }
  }
  return keyStr
}
console.log(getKeys(data, 'str6'))
function getKeys(obj, value) {
    for (var key in obj) {
        var val = obj[key];
        if (val === value) {
            return key;
        } else if (val && typeof val === "object") {
            var _key = getKeys(val, value);
            if (_key.length) return key + " " + _key;
        }
    }
    return "";
}
console.log(getKeys(data, "str6"));
    function getKey(data, key, arrTemp) {
        for (let v in data) {
            let arr = [];
            arr = arr.concat(arrTemp);
            if (data[v] == key) {
                arr.push(v);
                var res = arr.toString()
                console.log(res);
                return res;
                
            }
            if (typeof data[v] == 'object') {
                arr.push(v);
                getKey(data[v], key, arr);
            }
        }
    }
    var data = {
        key1: 'str1',
        key2: {
            key3: 'str3',
            key4: 'str4',
            key5: {
                key6: 'str6'
            },
            key8: {
                key9: 'str9'
            }
        },
        key7: "str7"
        // ...
    }
    getKey(data, "str6", [])
// 存储结果
let arr = []
// 寻找到的标记
let mark = false
/**
 * @author: 周靖松
 * @information: 寻找函数
 * @Date: 2019-07-09 13:45:43
 */
function getKey(model, value) {
    for (const key in model) {
        // 是字符串且符合寻找的值
        if (typeof model[key] == 'string' && model[key] == value) {
            // 把key塞进去
            arr.push(key)
            // 标记已经找到
            mark = true
        } else if (typeof model[key] == 'object') {
            // 把key塞进去
            arr.push(key)
            // 递归(视情况而定,不推荐递归,层级深可以考虑while)
            getKey(model[key], value)
            // 寻找到则跳出
            if (mark) break
            // 递归回来且没找到弹出key
            arr.pop()
        }
    }
    // 返回储存结果
    return arr
}
// 闭包了,哈哈哈 ,不走寻常路,玩玩就好了不推荐这么写
console.log(getKey(data, 'str9'))
function  getKeys(data,str){
    var result=[];
    function recursion(data,str){
        for(var key in data){
            if(data[key] == str){
                result.push(key);
                return result;
            }
            if(typeof data[key] == 'object'){
                result.push(key);
                return recursion(data[key],str)
            }else{
                return;
            }
        }
    }
    recursion(data,str);
    return result.join(' ');
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏