简体   繁体   中英

Search in an array of objects and return a value from the last corresponding Object in JS

I'm struggling to return a value for last event containing "SearchResults" in the case below: schema of my datalayer where I want to collect the information

At the moment I achieved to write to following code in order to know if a SearchResult event exists or not:

    //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 take the last one that was generated and return the pageIndex value of that one
    console.log("exist");  
    } else {
        // If it doesn't exist return 1
        return 1;
  };

Now I'm struggling to find a way to select only the last event generated and return the value contained in "digitalData.event.attributes.pageIndex".

Does anyone have any solution regarding this point?

Thank you,

You could just save that in a variable temporarily and return the last result. Is this what you wanted?

const searchResults = digitalData.event.filter(e => e.componentID === 'SearchResults')
if (searchResults.length > 0) {    
    const yourAnswer = searchResults[searchResults.length -1]
    console.log("exist");  
    } else {
        
        return 1;
  };

Filter the items first, and if there are any take the last item:

const searchResults = digitalData.event.filter(e => e.componentID === 'SearchResults');
if (searchResults.length > 0) {
  // If there are any that exist, I want to take the last one that was generated and return the pageIndex value of that one
  return searchResults[searchResults.length-1].pageLength;
} else {
  // If it doesn't exist return 1
  return 1;
};

Hello bro you can do what you want in this way.

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

    console.log(getResult)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM