Accessing the parent object in a multi-level object array using JavaScript

I am dealing with a multi-dimensional array where each object shares 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"
    }
]

I need to retrieve the parent object based on a specific key and value pair (e.g. path: '/b/1') within the array.

The expected result when using { path: '/b/1' } should be as follows:

{
        "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 root array will be returned (equivalent to MENU). If you have a solution to this problem, please share it with me. Thank you.

Answer №1

def find_object_in_array(array, key, value):
  return next((item for item in array if is_item_present(item)), None)

def is_item_present(current):
  entries = current.items()
  for k, v in entries:
    if k == key and v == value:
      return True
    if isinstance(v, list):
      for f in v:
        if is_item_present(f):
          return True
    if isinstance(v, dict) and v is not None:
      if is_item_present(v):
        return True

# usage
obj = find_object_in_array(MENUS, 'path', '/b/1')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The success function in Ajax Jquery is not triggering

I am facing an issue with my jQuery code where it always triggers the error function: function getStatistic6() { var response; var allstat6 = []; var dstart = "01.01.2014"; var dend = "03.31.2014"; $.ajax({ type: 'GET', url: 'http: ...

Tips for implementing autocomplete in a textbox on an ASP.NET website with jQuery

Make sure to include a control named ProductType of type textbox in your .aspx page. [WebMethod(EnableSession = true)] public static List<string> GetAutoCompleteDataProduct(string ProductType) { // string pid = ""; ProductMas ...

While working on a C program, I randomly incremented certain integer elements within an array. Surprisingly, values that were left unchanged ended up being altered. How did

My dilemma revolves around an integer array containing 400 elements. Initially, I set each element to 0 and verify that it is indeed 0 because the behavior puzzles me. Subsequently, I randomly select 10,000 indices to increment the corresponding array ele ...

Bootstrap Collapse feature fails to collapse on Twitter

I'm having trouble with the bootstrap collapse navbar. It expands fine, but I can't seem to collapse the navigation. Everything seems correct in my code: <nav class="navbar navbar-inverse nav-justified"> <div class="navbar- ...

How to Implement Recursive Function Calls in JavaScript?

My goal is to create an interactive function using HTML and jQuery. I am utilizing jQuery to update and change attributes and text for a more seamless experience without page reloads, especially since it's not image-heavy. I have structured "scenes" ...

Tips on leveraging JQuery's $.when for handling ajax requests sequentially

How can I effectively use $.when in JQuery with chained promises to ensure my ajax requests are processed in the correct order? I have a dynamic array called costArray containing various objects. For each item in this array, I initiate an Ajax request nam ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Is there a way to prevent a background video from automatically playing whenever the user navigates back to the home page?

Recently, I was given a design that requires a background video to load on the home page. Although I understand that this goes against best practices, the client has approved the design and now I need to come up with a solution. The video is already in pla ...

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

What is the best way to create rotational movement for an object in a-frame?

Is there a way to have my entity rotate/spin on the Y-axis? I attempted the following: <a-entity position="-1 0.5 3" animation="property: rotation; to: 0 0 0 ; loop: true; elasticity:1000; dur: 10000" rotation="90 0 0"> <a-box position="1 0 ...

What is the best way to trigger the Save as ..dialog by clicking on an image?

Below is the code snippet provided. When the link is clicked, a save as dialog should pop up. <a href="http://www.experts-exchange.com/xp/images/newNavLogo.png" target="_new"> <img src="http://www.experts-exchange.com/xp/images/newNavLogo.png" a ...

What steps can I take to restrict a draggable element to the body, prevent text selection, and allow form inputs to be enabled?

I'm currently utilizing the react-draggable library for my project. In order to ensure that the element remains within the confines of the body element, prevent text selection, and allow interaction with form inputs inside the draggable element, I en ...

What are the best techniques for implementing opacity in styled components within react-native?

Trying to achieve a lighter background color using opacity in react-native with styled-components. I'm looking to make the background appear faded by adjusting the opacity level, but nothing seems to happen when I apply my code. Any suggestions on h ...

`troubles integrating external modules in nuxt application`

Just starting with nuxt and incorporating it with vuetify. My aim was to integrate a Google Places Autocomplete feature, so I stumbled upon this: vuetify-google-autocomplete. It seemed simple enough to implement. But turns out it's not that straightfo ...

Difficulties encountered when attempting to populate a select dropdown with data fetched through an AJAX request

Currently, I am working on a small project that involves managing libraries. One of the tasks at hand is populating a select tag with all the libraries stored in my database. To accomplish this, I have developed a WebService which features a web method cal ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

What is the process for removing a range of keys from indexeddb?

I need help deleting keys that start with tracklist/RANDOM_STRING and 'songBook/RANDOM_String'. I attempted to do this using IDBKeyRange but I am struggling to understand how it works. The documentation I referred to was somewhat confusing: Mdn ...