簡體   English   中英

如何檢查某個值是否存在於將對象作為其元素的數組中。 JavaScript

[英]How to check if a certain value exist in an array which holds objects as its elements. JavaScript

第一個是當我們有一個數組包含字符串等常規元素並且我知道如何在其上使用 Includes 時。

但是 arrays 將對象作為元素呢? 我如何檢查這些對象中是否有特定值?

 const arr = ['this', 'is', 'a test']; console.log(arr.includes('this')); const arr2 = [ { id: '123', name: 'Alex' }, { id: '345', name: 'Dan' }, { id: '33', name: 'Joe' }, ];

您可以使用some function。

const arr2 = [
  { id: '123', name: 'Alex' },
  { id: '345', name: 'Dan' },
  { id: '33', name: 'Joe' },
];

console.log(arr2.some(item => item.name==="this" ))

some()方法測試數組中是否至少有一個元素通過提供的 function 實現的測試。

如果你想要一個返回的值數組匹配=>

 const filtered = arr2.filter((item)=>item.name == 'value')

如果你想要 bool(true||false) =>

 const filtered = arr2.filter((item)=>item.name == 'value').length > 0

或使用上面提到的一些。

暫無
暫無

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

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