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

What makes CVE-2021-33623 susceptible to ReDoS attacks?

CVE-2021-33623 points out that the code snippet below (addressed in this commit, along with test cases) is susceptible to ReDoS vulnerabilities: trimNewlines.end = string => string.replace(/[\r\n]+$/, ''); What makes it prone to ReD ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

What causes a syntax error when trying to create an array of objects within a map using colons?

In my Google Apps Script, I created a function to retrieve the date and subject of emails with a specific label in Gmail. However, when attempting to store each result as an object, I encountered a SyntaxError: unexpected token ':' issue. Althoug ...

Response from a Clean jQuery Web Service

I've been seeing a lot of code examples calling web services that return JSON data, but they tend to involve back-end languages like PHP. Does anyone know of a tutorial for a jQuery-only solution? For example, setting up div tags with IDs, then direct ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Exploring image manipulation techniques through exercises with np.array indexing

I recently came across an exercise on a website that I'm trying to understand. The task involves removing grains smaller than 10 pixels from a picture of sand viewed under a microscope. You can find the exercise here. sand_labels, sand_nb = ndimage.la ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

Steps to display a text box once the dropdown list is updated

I have a dropdown menu with two options <div class="form-group"> <span class="col-sm-4 control-span">Member Type</span> <div class="col-sm-8"> <select class="form-control" id="membertype" name="me ...

`Why the find method in C++ is returning incorrect results?`

When working with the following code, our first task is to calculate the weights of uniform substrings present in the strings. Uniform substrings are those that consist of only one character, such as "a" or "aaa". The weight of each character is defined fr ...

Having trouble with state not updating correctly after making a fetch request within a useEffect hook in

In my React app with an Express backend, I am facing a challenge in updating the component state using the useEffect hook to trigger once when the component renders. Inside the useEffect, I fetch data from the Express server. const Favorites = ({ user }) = ...

Styling an active link in Next.js using Styled Components

Looking for a way to customize the active link style using styled components. I have a navigation bar where the currently active link should have a specific style applied. Any suggestions are appreciated! import React from 'react' import Link f ...

Is it possible to modify the CSS styles for a specific portion of an input value?

Currently, I am in the process of developing a form using React.js where a specific input must match the label written above it. Here is an example: https://i.stack.imgur.com/S2wOV.png If there happens to be a typo, the text should turn red like this: h ...

`Enhance Image with a Fresh Hue`

Let me explain my dilemma: I'm dealing with a two-tone png image - one tone is black and the other is transparent. Right now, I'm relying on the background color attribute to dynamically change the color of the transparent section. However, I ...

Conceal any elements that have a class containing specific text

In my HTML file, I have multiple <span> elements with the class of temp_val that include a 1 value which I need to hide. These elements are placed throughout the document. Below is an excerpt from my HTML code: <div class="row" style="float: lef ...

What is the best way to transfer scope to a callback function in the context of node-mysql?

When running the code below, I encounter an error that says client is not defined: var mysql = require('mysql'); var conf = { 'database':'database', 'user':'user', 'password':'password ...

Experiencing difficulty retrieving data by ID using CodeIgniter with JSON

Currently, I am retrieving the name of sub_regions based on their corresponding region_id using ajax. Upon joining the region and sub_region table, I can view the results within the Google Chrome console. This indicates that the query and other operations ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...