遍历获取密钥和所有父密钥的对象 [英] Traversing an object getting the key and all parents keys

查看:119
本文介绍了遍历获取密钥和所有父密钥的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遍历树(json),使用JS实现getKeys(data,str)函数.得到钥匙和所有父母钥匙.

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',
    },
  }
}

例如:

getKeys(data,'str1'); 返回:"key1"

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

getKeys(data,'str3'); 返回:'key2,key3'

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

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

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

推荐答案

您的代码存在的问题是,无论该值实际上是否在当前处理的分支下,它都会无条件地填充找到的"列表.考虑例如:

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,
        },
    }
};

执行getKeys(data, 44)时,返回值为[ 'b', 'd', 'e', 'f', 'f2' ],这是不正确的.

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

    }
}

这篇关于遍历获取密钥和所有父密钥的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆