Is it possible to pass an additional parameter through the function called by the Array.forEach method?

I have created an array named allchildsAr and I am populating it with objects that contain a parent property (an object) and a chlds property which is an Array.

Here is the code to fill the array :

Ti.API.info("*****allchildsAr["+level+"] is null and "+elmn+" children will be added to it ");
allchildsAr[level] = new Array({parent:elmn,chlds:elmn.getChildren()}); 

After adding elements to the array, I attempt to display its contents:

  Ti.API.info("*****allchildsAr["+level+"] after add");
allchildsAr[level].forEach(logArrayJsonElements);

The logArrayJsonElements method looks like this:

function logArrayElements(elemnt, indx, array) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.id);
}

function logArrayJsonElements(elemnt, indx, array) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.parent.id);
    elemnt.chlds.forEach(logArrayElements);
}

While this setup is effective, I now want to pass the parent element through logArrayElements so I can display it as the parent of the array's displayed element (and perform other operations later on). This has led me to modify the logArrayElements function as follows:

function logArrayElements(elemnt, indx, array, parent) {
    Ti.API.info("*****Element at [" + indx + "]   : " + elemnt.id+" child of :"+parent);
}

However, I am facing confusion as when logArrayElements is called within forEach, arguments are not explicitly passed. If I include the parent parameter as intended, it gets confused with another parameter (usually the element parameter). How do I get the parent inside the function and ensure forEach passes it along with other parameters?

Answer №1

To achieve this task, adjust your forEach line as follows:

function displayJsonElements(element, index, array) {
    console.log("*****Element at [" + index + "]   : " + element.parent.id);
    element.children.forEach(function (child, idx, arr) {
        displayArrayElements(child, idx, arr, element.parent.id);
    });
}

Answer №2

Why not simply utilize element.parent if it already exists within the element in the function logArrayElements?

If the elements have different data structures, you can make use of bind to partially apply. Here's an example:

function logArrayElements(parent, element, index, array) {
    console.log("Element at [%s] : %s is a child of %s", index, element.id, parent);
}

function logArrayJsonElements(element, index, array) {
    element.children.forEach(logArrayElements.bind(null, element.parent));
}

Answer №3

When working within the logArrayJsonElements function, bind the logArrayElements function to an object with the parent property set to itself.

function logArrayJsonElements(element, index, array) {
    Ti.API.info("*****Element at [" + index + "]   : " + element.parent.id);
    element.children.forEach(logArrayElements.bind({parent: element.parent}));
}

The statement

logArrayElements.bind({parent: element.parent})
creates a new Function object with the context set to {parent: element.parent}, allowing you to access the parent object using this.parent.

To make this work, update the logArrayElements function to remove the parent parameter and instead use this.parent to reference the parent object:

function logArrayElements(element, index, array) {
    Ti.API.info("*****Element at [" + index + "]   : " + element.id + " child of :" + this.parent);
}

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

Error: Trying to access "dishes" property on an undefined object gives a TypeError

Need Assistance Urgently! I have developed a web application using react and integrated it with node js. In the app, I am required to pass the status of a dish to the DishDetail Component indicating whether it is marked as "Favorite" or not. If a dish is ...

Issue with JQuery Ajax: Some users experiencing failure with ajax requests (response code 0)

I've implemented an ajax-based login system where users input their username/password and the data is asynchronously sent to a PHP script for validation. Once validated, the user is logged in or an error message is returned in JSON format. However, I ...

Retrieving output from a JavaScript function

When running the code, the following logs are generated: "generating my graph" myMain.js:110 "Getting credits" myMain.js:149 "debits array is 3.9,4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8" myMain.js:169 "Credits data = 10.7,20.5" myMain.js:156 ...

Applying custom CSS to individual divs based on their text height using jQuery

I have a grid consisting of multiple boxes each sized at 280px by 280px, and I am seeking a way to vertically align text within hover overlays on each box. While my current code successfully aligns the text for the first box, I am encountering issues due ...

Efficient method for identifying the positions of non-zero elements in a 2-dimensional array using Python

In questioning the efficiency of the numpy.nonzero function, I ran a test to compare its performance under different conditions. Here is an example: a=np.random.random((1000,1000)) a[a<0.5]=0 timeit.timeit(lambda:np.nonzero(a),number=100)/100.0 #gives ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

"Utilizing the useState hook to selectively update a portion of the state while keeping the remaining state unchanged

Hello there, I have a question. Is it possible to update just a portion of the state while keeping other parts the same in React? const stuff ={ 'a':'alpha', 'b':'beta' }; const [letter,setLetter]=useState(stuff); ...

Looking to grasp the concept of calling inline functions within a React functional component

As a newcomer to React, I recently created a new view within my company. Following the example of many guides, I have utilized inline functions and function components exclusively. One common practice I have adopted is writing onClick events in this manne ...

Connect external script actions to HTML elements within components

I'm attempting to incorporate an external script Within public/index.html <script src="https://embed.selly.gg"></script> An event should trigger when I click on a button with specific data attributes. Inside components/shop/ShopItem.js ...

Using JavaScript to display a hidden element when clicked within an overflow-auto container

I have a collection of items grouped within a container with overflow-auto applied. When clicked, I want to scroll/place an item all the way to the right if possible. This will trigger the other items to auto-scroll to the left, positioning the clicked it ...

Material-ui library causing complications in rendering React components

Encountering an issue with React and the material-ui library – my cards are displaying vertically instead of horizontally aligned side by side. Though I attempted to adjust the react grid component, it did not resolve the problem. Current Output: https: ...

The access to the HTTP request has been restricted

Currently, I am developing multiple applications that need to communicate with each other. To test these apps, I am using both Chrome and Firefox browsers. Strangely, the issue persists in both browsers. The issue at hand: In one of my applications (let& ...

When implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

Multiple executions of Google API sign in listener

I have been working on a Vue module that allows users to add events to Google Calendar easily. Once a user signs in, there is a listener in place to call a method for adding an event to the calendar. To access the gapi functionalities required for this tas ...

Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly: $('#ddl').change(function () { $('#cont').html(''); var count = getCount($('#ddl').val()) for (var i = 0; i < count ; ...

What could be causing my browser to display "uncaught referenceerror" in this situation?

Just running some browser tests to troubleshoot - everything's smooth sailing until this line is reached: responseJson = JSON.parse(localReq.responseText); So, when I evaluate JSON.parse(localReq.responseText), the correct value comes through. But a ...

Expanding the functionality of Promise to include progress updates

I had the idea to expand Promise by adding a 'progress' feature in order to track progress while using Promise for my asynchronous tasks. So, I created an extended version of Promise like this: class promisePro extends Promise { constructor ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

What method should be used to transfer a pointer as a parameter to a function?

If I create a function that prints out elements of a multi-dimensional array, how can I ensure it works correctly? int print(int *a) { for (int i=0;i<4;i++) { for(int j=0;j<4;j++) { cout<< *((a+i*4)+j);} } } return 0;} When attempting to c ...

The Google Maps display for this page failed to load properly on the map

<!-- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> --> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize" async="" defer="defer" type="text/javascript">& ...