获取深度嵌套对象中特定键的所有路径

时间:2020-02-22 13:08:20

标签: javascript object recursion

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

例如:

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]

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

1 个答案:

答案 0 :(得分:0)

您可以使用for...in循环来创建递归函数。

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