-->

Traversing an object getting the key and all paren

2020-07-30 00:34发布

问题:

traverse tree(json), fulfill getKeys(data, str) function using JS. get the key and all parents keys.

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

for example:

getKeys(data, 'str1'); return: 'key1'

getKeys(data, 'str3'); return: 'key2, key3'

getKeys(data, 'str6'); return: 'key2, key5, key6'

I think it can be done be recursion, but how?

this is my solution, but failed

let s = [];
function getKeys(data, str, key='') {
  if (key !== '') {
    s.push(key);
  }
  for (item in data) {
    if (typeof data[item] === 'object') {
      getKeys(data[item], str, item);
    } else if (data[item] === str) {
      s.push(item);
      return s;
    }
  }
  return s;
}

回答1:

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];

    }
}


回答2:

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', []));