簡體   English   中英

返回單個項目的嵌套 for 循環的功能等價物

[英]Functional Equivalent of nested for loops to return a single item

所以我讓這個 function 在嵌套的 object 中循環並返回滿足最內層條件的第一個項目。 所以最后我們只會返回一個(或無)object。 我嘗試使用嵌套find ,但最終得到了原始有效負載。 所以我結束了使用下面所示的嵌套for循環方法。

const getMostGranular = (facets) => {
  for (let facet of facets) {
    for (let item of facet.hits) {
      if (getMonthsFromNow(item._source.publish_date) <= 6) {
        return item._source;
      }
    }
  }
};

是否有一種看起來不那么丑陋的更“實用”的方法?

const getMostGranular = 
  facets
    .flatMap(facet => facet.hits)
    .find(item => getMonthsFromNow(item._source.publish_date) <= 6);

我認為只需將事物移動到單獨的函數中,並利用recursion之類的東西(而不是for循環)

 const getHits = (needle, [head, ...tail]) => { if (head?.months === needle) { return head; } return tail.length? getHits(needle, tail): null; } const getMostGranular = (needle, [{ hits = [] }, ...tail]) => getHits(needle, hits)?? ( tail.length? getMostGranular(needle, tail): null ); const tree = [ { hits: [{ months: 1 }] }, { hits: [{ months: 10, }] }, { hits: [{ months: 11, }] }, { hits: [{ months: 12, source: { message: 'You found me' }, }] }, { hits: [{ months: 13, }] }, { hits: [{ months: 14, }] }, ]; console.log( getMostGranular(12, tree), );

暫無
暫無

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

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