在对象数组中搜索 return JS 中最后一个对应对象的值

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

我正在努力 return 在以下情况下包含“SearchResults”的最后一个事件的值: schema of my datalayer where I want to collect the information

目前我编写了以下代码以了解 SearchResult 事件是否存在:

    //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;
  };

现在我正在努力寻找一种方法来 select 仅生成最后一个事件和 return “digitalData.event.attributes.pageIndex”中包含的值。

有没有人对此有任何解决方案?

谢谢,

您可以将其暂时保存在一个变量中,return 最后的结果。这是你想要的吗?

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;
  };

先过滤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;
};

你好兄弟,你可以用这种方式做你想做的事情。

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)