Explore an array of objects to find and retrieve a value from the final matching object in JavaScript

I'm having difficulty retrieving the value for the last event that includes "SearchResults" in the scenario outlined below: Here is a schema of my datalayer where I am looking to gather information.

Currently, I have managed to write the following code to determine if a SearchResult event exists:

    //Check if an existing event contains Search Results
if (digitalData.event.filter(e => e.componentID === 'SearchResults').length > 0) {    
    // If there are any that exist, I want to retrieve the pageIndex value of the last one generated
    console.log("exist");  
    } else {
        // If it doesn't exist, return 1
        return 1;
  };

Now, I am facing challenges in figuring out how to specifically select the most recent event generated and fetch the value stored in "digitalData.event.attributes.pageIndex".

Does anyone have a solution for this issue?

Thank you,

Answer №1

If you store that information in a variable temporarily, you can easily retrieve the last result when needed. Does this approach align with your expectations?

const searchResults = dataStream.events.filter(item => item.id === 'SearchResults');
if (searchResults.length > 0) {    
    const finalResult = searchResults[searchResults.length -1];
    console.log("Found");  
    } else {
        return 1;
  };

Answer №2

To start, filter out the items and then select the last item:

const filteredResults = digitalData.event.filter(item => item.componentID === 'SearchResults');
if (filteredResults.length > 0) {
  // If there are any matches, grab the pageIndex value of the last generated item
  return filteredResults[filteredResults.length-1].pageLength;
} else {
  // If no matches found, return a default value of 1
  return 1;
};

Answer №3

Hey there, feel free to explore your options using this method.

let findResult = digitalData.event.filter(event => event.componentID === 'SearchResults' && event.componentID.length > 0 )
  
    if (findResult.length > 0) {
    const found = findResult[findResult.length - 1];
    findResult = found
    } 

    console.log(findResult)

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

How can I delete the onmouseover function in HTML?

Is there a way to remove the (onmouseover="mouseoversound.playclip()") function from the following HTML code? <a href="roster.html" onmouseover="mouseoversound.playclip()">Roster</a> Can we instead implement this functionality in a JavaScript ...

How do I implement the use of "lengthMenu: [10, 25, 50]," within an if/else statement effectively?

Could someone help me with defining 2 different configuration lines for a datatable using if-else statements? I've tried writing the code but it doesn't seem to be working as expected. if(role === 1) { lengthMenu: [10, 25, 50], } else ...

When the result of Ajax is identical to that obtained without Ajax, the innerHTML remains the same

I understand that utilizing innerhtml is generally considered a poor practice due to the potential for XSS vulnerabilities (). However, consider the scenario below: I have a webpage generated through a Twig template called index.html.twig. When using te ...

Angular 4 applications do not come with TinyMCE embedded

I've been attempting to integrate the tinyMCE editor into an angular4 application, but unfortunately I encountered an error that reads: tinyMCE is not defined. https://i.stack.imgur.com/qMb5K.png I have been following the guidance provided by tin ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Modify the color of a div element in React when it is clicked on

My goal is to change the color of each div individually when clicked. However, I am facing an issue where all divs change color at once when only one is clicked. I need help in modifying my code to achieve the desired behavior. Below is the current implem ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Is the data set in stone, or is it just the API data that can

Recently, I embarked on the journey of creating a blog using nextjs, MongoDB, and express. Taking advantage of getStaticProps and getStaticPaths, I was able to dynamically generate pages for each blog post and display them individually. However, I encoun ...

Oops! An error has occurred: The requested method 'val' cannot be called on an undefined object

I am struggling with this issue. This is the code that I am currently working on: http://jsfiddle.net/arunpjohny/Jfdbz/ $(function () { var lastQuery = null, lastResult = null, // new! autocomplete, processLocation = function ...

A tutorial on making a POST request using axios in a React application

I am struggling with my JavaScript skills I need assistance with calling the following CURL command successfully: curl -X POST -H "Content-Type: application/json" -u john.doe:moqui -d "{\"firstName\":\"Hung&bso ...

Is AngularJS the right choice for developing this application?

Recently, I've come to the realization that I want to dive into the world of AngularJS framework after working with jQuery for several years. I have a vision of developing an application that allows users to easily modify webpage DOM using a browser- ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Challenge implementing custom javascript to display categorical/string features on Shiny slider

I'm attempting to design a unique Shiny slider that represents the months of the year. My desired outcome is for the slider to display the names of the months as strings, rather than numeric values where 1 corresponds to January, 2 corresponds to Febr ...

Angular front-end rendering with Rails backend integration

Currently, I am working on a medium-sized Rails application and my latest endeavor is to integrate Angular into the system. After reviewing several tutorials, it appears that the most common method for fetching initial data and displaying the first view in ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Form a collection and calculate

Greetings from France, I hope my message finds you well! I recently spent a year in the USA, but now back in France... Let me share some code snippets with you. I have received this data from a form: cmdId[] 25 cmdId[] 26 cmdId[] 27 cmdId[] 28 cmdId[] 29 ...

Issue detected: Click event for Backbone not properly registered

Hey there, I'm new to Backbone.js and having some trouble with a login feature. Despite initiating the view, I can't seem to get the click event to fire during an ajax call for logging in. Any ideas on what I might be doing wrong? I've even ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...