Traversing an object getting the key and all parents keys

大兔子大兔子 提交于 2019-12-04 19:46:12

The problem with your code is that it populates the "found" list unconditionally, no matter if the value is actually under the currently processed branch or not. Consider for example:

data = {
    a: 1,
    b: {
        c: 2
    },
    d: {
        e: {
            e1: 3,
            e2: 33,
        },
        f: {
            f1: 4,
            f2: 44,
        },
    }
};

when doing getKeys(data, 44), the return will be [ 'b', 'd', 'e', 'f', 'f2' ], which is not correct.

What you need to do is to check if the value is actually under the current node and add the current key only if the answer is yes. Example:

function getKeys(obj, val) {
    if (!obj || typeof obj !== 'object')
        return;

    for (let [k, v] of Object.entries(obj)) {
        if (v === val)
            return [k];
        let path = getKeys(v, val);
        if (path)
            return [k, ...path];

    }
}

Assuming you are only searching for string keys we can use recursion & backtracking to check if the sub-object of a key is having the specified value.

If it has it then add the parent key in our final search string.

To do this I have used Object.entries() to go over every [key, value] pair and used Array.prototype.reduce() to accumulate the results:

var data = {
  key1: 'str1',
  key2: {
    key3: 'str3',
    key4: 'str4',
    key5: {
      key6: 'str6',
      key7: 'str7',
      key8: 'str8',
    },
  }
}

function getKeys(data, key, acc){
   return Object.entries(data).reduce((acc, ele, idx) => {
     if(ele.includes(key) && typeof ele[1] === "string"){
        acc.push(ele[0]);
     }
     if(typeof ele[1] === "object" && !Array.isArray(ele[1]) && !(ele[1] instanceof Date)){
        let old = acc.slice();
        getKeys(ele[1], key, acc); 
        if(old.length !== acc.length){
           acc.unshift(ele[0]);
        }
     }  
     return acc;
  }, acc).join(" ");
}


console.log(getKeys(data, 'str1', []));
console.log(getKeys(data, 'str3', []));
console.log(getKeys(data, 'str6', []));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!