【问题标题】:Get specific key depth in object with key value获取具有键值的对象中的特定键深度
【发布时间】:2019-03-08 17:13:58
【问题描述】:
const item = {
  id: 'item1',
  children: [ 
    { id: 'item1-1',
      children: [
        { id: 'item1-1-1' },
        { id: 'item1-1-2' },
        { id: 'item1-1-3' },
      ]
    },
    { id: 'item1-2',
      children: [
        { id: 'item1-2-1' }
      ]
    }
  ]
}

这样,

function getLevelOfId(){
  ...
}

getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3

如何使用 JavaScript 获取特定对象的深度?

不使用id 字符串。比如('item1-2').split('-').length 因为每个对象都有随机的id。有没有简单的方法?

【问题讨论】:

  • 嗨!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. (您可能想要使用递归。)如果在进行更多研究和搜索后您遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example并具体说出你卡在哪里。人们会很乐意提供帮助。
  • @SouritraDasGupta 不一样。这个问题是关于 maximum depth 的,这是关于 specific depth 的。

标签: javascript


【解决方案1】:

您需要迭代所有对象,如果找到,则为递归深度的每个级别取一个。

function getLevelOfId(object, id) {
    var level;
    if (object.id === id) return 1;
    object.children && object.children.some(o => level = getLevelOfId(o, id));
    return level && level + 1;
}

const item = { id: 'item1', children: [{ id: 'item1-1', children: [{ id: 'item1-1-1' }, { id: 'item1-1-2' }, { id: 'item1-1-3' }] }, { id: 'item1-2', children: [{ id: 'item1-2-1' }] }] };

console.log(getLevelOfId(item, 'item1'));     // 1
console.log(getLevelOfId(item, 'item1-2'));   // 2
console.log(getLevelOfId(item, 'item1-1-1')); // 3
console.log(getLevelOfId(item, 'item1-1-2')); // 3
console.log(getLevelOfId(item, 'foo'));       // undefined

【讨论】:

    【解决方案2】:

    如果结构id&children是固定的,那么如何在json字符串中搜索像“item1-1-1”这样的整个值:

    {"id":"item1","children":[{"id":"item1-1","children":[{"id":"item1-1-1"},{"id ":"item1-1-2"},{"id":"item1-1-3"}]},{"id":"item1-2","children":[{"id":"item1 -2-1"}]}]}

    level = (number of "{") - (number of "}") // 在搜索到的字符串位置之前

    【讨论】:

    • itemitem1-1-1和itemitem1-1-2的case,这两个是同级的。也许两者的结果会有所不同。
    • 如果结构是固定的,结果是一样的,如图,也考虑了“}”的个数,所以item1-1-1 = 3 - 0, item1-1-2 = 4 - 1
    • 哦,我不知道。那讲得通!我也要试试这个方法!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多