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,
CodePudding user response:
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;
};
CodePudding user response:
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;
};
CodePudding user response:
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)
