簡體   English   中英

在對象數組中搜索並返回JS中最后一個對應的Object的值

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

在以下情況下,我正在努力為包含“SearchResults”的最后一個事件返回一個值:我想要收集信息的數據層的架構

目前,我實現了編寫以下代碼以了解 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 僅生成最后一個事件並返回“digitalData.event.attributes.pageIndex”中包含的值。

有人對此有任何解決方案嗎?

謝謝,

您可以將其暫時保存在變量中並返回最后一個結果。 這是你想要的嗎?

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

首先過濾項目,如果有則取最后一個項目:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM