获取深度嵌套对象中特定键的所有路径 [英] Get all paths to a specific key in a deeply nested object

查看:33
本文介绍了获取深度嵌套对象中特定键的所有路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在深度嵌套的对象中递归搜索特定键.

How do i recursively search for a specific key in a deeply nested object.

例如:

let myObject = {a: {k:111, d:3},  b:"2", c: { b: {k: 222}}, d: {q: {w: k: 333}}} }
let result  = findAllPaths(myObject, "k")

// result = [a.k, c.b.k, d.q.w.k]

结果应该是嵌套对象中任何位置的键的所有路径的列表

The result should be a list of all paths to the key anywhere in the nested object

推荐答案

您可以使用 for...in 循环创建递归函数来执行此操作.

You could create recursive function to do this using for...in loop.

let myObject = {a: {k:111, d:3},  b:"2", c: { b: {k: 222}}, d: {q: {w: {k: 333}}} }

function getAllPaths(obj, key, prev = '') {
  const result = []

  for (let k in obj) {
    let path = prev + (prev ? '.' : '') + k;

    if (k == key) {
      result.push(path)
    } else if (typeof obj[k] == 'object') {
      result.push(...getAllPaths(obj[k], key, path))
    }
  }

  return result
}

const result = getAllPaths(myObject, 'k');
console.log(result);

这篇关于获取深度嵌套对象中特定键的所有路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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