Finding the required object from a submenu in an array using JavaScript

Hi there, I'm having some trouble with my code below. I am trying to print the title object from the submenu object, but I keep getting this error: Output: undefined 2 3

Here is the code:

const menu = [
        {
            title : "1",
            submenu :[
                {
                    title : 'gilbert lua',
                },
                {
                    title : 'pemai',
                },
            ],
        },
        {
            title : "2",
        },
        {
            title : "3",
        }
    ];
    
const data = menu.map((e)=> {
    test(e.submenu,e.title)
});
function test(e,f){
    // const submenu = e.title;
     const testing = e? (e.title) : (f);
     console.log(testing);
}

Thank you

Answer №1

The logic behind the code

const testing = e? (e.title) : (f);
is that if the variable e is not null, it represents an array, and we can then utilize the forEach method to iterate over and print the elements in this array.

Note: It is generally discouraged to use the map method for iterating over elements instead of the more appropriate forEach method.

const menu = [
        {
            title : "1",
            submenu :[
                {
                    title : 'gilbert lua',
                },
                {
                    title : 'pemai',
                },
            ],
        },
        {
            title : "2",
        },
        {
            title : "3",
        }
    ];
    
const data = menu.map((e)=> {
    test(e.submenu,e.title)
});
function test(e,f){
     if(e){
       e.forEach(i => {
         console.log(i.title)
       })
     }else{
       // based on your question, this line may possibly be unnecessary
       console.log(f)
     }
}

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

Designing a system that effectively handles subtract requests from clients on a server

When a server receives requests on '/subtract', it should accept two parameters, 'a' and 'b', and then return the difference between them as a plain text response. I have already set up the server and added the necessary requ ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission. Firstly, I need to address this issue: fnPtr is not a function Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I ...

Combining PHP Arrays to Create a 2D Array

In the code below, we have two arrays: $array1 and $array2. $array1 is a unidimensional array, while $array2 is a 2D array: Array ( [coupon_code] => GTY777R [coupon_description] => Credit $5 USD ) Array ( [0] => Array ( ...

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

Utilizing React to implement a search functionality with pagination and Material UI styling for

My current project involves retrieving a list of data and searching for a title name from a series of todos Here is the prototype I have developed: https://codesandbox.io/s/silly-firefly-7oe25 In the demo, you can observe two working cases in App.js & ...

What could be causing the CastError: Cast to ObjectId failed in my code?

Whenever I try to access a specific route in my project, the following error is returned: Server running on PORT: 7000 /user/new CastError: Cast to ObjectId failed for value "favicon.ico" (type string) at path "_id" for model "User" at model.Query.exe ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet. Is there an alternative method to optimize this process without utilizing map? Code: const arr = [{ label: 'A', ...

Experiencing difficulties while iterating through a basic JSON array

When I iterate through the ajax array, the index and value are being displayed incorrectly. $.ajax({ url: '/ajax/deal_start_times/' + $pid, success: function(data){ var tmp = ""; $.each(data, function(index, value) { ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

Difficulty encountered when trying to use Bootstrap tooltip with Bootstrap icon

Attempting to implement bootstrap tooltips on bootstrap icons with the following code: <body> <script> const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

What is the best way to transform an integer array into a single integer value

I'm interested in learning how to convert an array of integers into a single integer in C#. My goal is to combine the integers from the array and create a new single integer. For instance: int[] myArray = {5, 6, 2, 4}; I would like this array to b ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

What could be the reason behind the appearance of borders in my modal window?

I can't seem to find the source of the 2 silver borders in my modal. I've checked the CSS code, tried using developer tools, and looked through the entire code but still can't figure it out. Here is the JSX code I'm working with: impor ...

How to submit a textarea with the enter key without needing to refresh the page

I'm attempting to handle the submission of a textarea when the user hits the enter key, storing the text in a variable, then swapping out the form with the text and adding a new form at the end, all without refreshing. I had success doing this with an ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...