如何获取多级对象数组中的父对象javascript

How to get parent object in multi-level object array javascript

我有一个多维数组,每个对象都有相同的键。

export const MENUS = [
    {
        "type": "main",
        "submenu": [],
        "path": "/a"
    },
    {
        "type": "main",
        "submenu": [
            {
                "type": "submenu",
                "submenu": [
                    {
                        "type": "submenu",
                        "submenu": [],
                        "path": "/b/4"
                    },
                ],
                "path": null
            },
            {
                "type": "submenu",
                "submenu": [],
                "path": "/b/1"
            }
        ],
        "path": null
    },
    {
        "type": "main",
        "submenu": [],
        "path": "/c"
    }
]

现在,我有一个键和值(路径:'/b/1'),我想通过数组中的 key/value 获取父对象。

这就是我在使用 { path: '/b/1' } 时寻找的结果。

{
        "type": "main",
        "submenu": [
            {
                "type": "submenu",
                "submenu": [
                    {
                        "type": "submenu",
                        "submenu": [],
                        "path": "/b/4"
                    },
                ],
                "path": null
            },
            {
                "type": "submenu",
                "submenu": [],
                "path": "/b/1"
            }
        ],
        "path": null
    },

如果我使用{path: '/c'},那么结果将是一个根数组。 (等于菜单) 如果谁有好的解决办法,请指教。 谢谢

function getObj(array, key, value) {
  return array.find(item => isThisItem(item))
  function isThisItem(current) {
    const entries = Object.entries(current)
    for (const [k, v] of entries) {
      if (k === key && v === value) return true
      if (Array.isArray(v)) {
        for (const f of v) {
          if (isThisItem(f)) return true
        }
      }
      if (typeof v === 'object' && v !== null) {
        if (isThisItem(v)) return true
      }
    }
  }
}

// usage
const obj = getObj(MENUS, 'path', '/b/1')