Home > Software engineering >  How to get parent object in multi-level object array javascript
How to get parent object in multi-level object array javascript

Time:04-21

I have a multidimensional array and each object has the same keys.

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"
    }
]

Now, I have a key and value (path: '/b/1') and I want to fetch parent object by key/value in array.

this is the result what I am looking for when I use { 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
    },

If I use {path: '/c'}, then the result will be a root array. (equal to MENU) If anyone has a good solution, please advise me. Thanks.

CodePudding user response:

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')
  • Related