簡體   English   中英

如果數組包含具有特定 id 的 object,則返回 true

[英]Return true if array contains object with specific id

我有一個名為過濾器的數組,其中包含對象。 在每個 object 中都有一個 id 和另一個數組,其中包含名為 filterItems 的對象。 如何檢查其中一個過濾器對象是否包含特定的 filterItems(例如 filterItems 是否包含 id“免費取消”)?

const filters = [
  {
    id: 'rateTypeFilter'
    filterItems: [
      {
        id: 'Free Cancellation'
      },
      {
        id: 'Pay Now'
      }
    ]
  },
  {
    id: 'fuelTypeFilter',
    filterItems: [
      {
        id: 'Gasoline'
      },
      {
        id: 'Hybrid'
      }
    ]
  }
],

使用Array.prototype.some

filters.some(obj => obj.filterItems.some(v => v.id === "Free Cancellation")) // true

或者,如果您想要特定的 object,請在外部使用Array.prototype.find

filters.find(obj => obj.filterItems.some(v => v.id === "Free Cancellation"))

您可以使用Array.prototype.some()兩次:

 const filters = [ { id: 'rateTypeFilter', filterItems: [ { id: 'Free Cancellation' }, { id: 'Pay Now' } ] }, { id: 'fuelTypeFilter', filterItems: [ { id: 'Gasoline' }, { id: 'Hybrid' } ] } ]; const result = filters.some(({ filterItems }) => filterItems.some(({ id }) => id === 'Free Cancellation')); console.log(result);

暫無
暫無

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

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