[英]How to check if a certain value exist in an array which holds objects as its elements. JavaScript
The first one is when we have an array holds regular elements like strings and I know how to use Includes on it.第一个是当我们有一个数组包含字符串等常规元素并且我知道如何在其上使用 Includes 时。
But how about arrays holding objects as their element?但是 arrays 将对象作为元素呢? How can I check if there is a certain value in those objects?我如何检查这些对象中是否有特定值?
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' }, ];
You can use the some
function.您可以使用some
function。
const arr2 = [
{ id: '123', name: 'Alex' },
{ id: '345', name: 'Dan' },
{ id: '33', name: 'Joe' },
];
console.log(arr2.some(item => item.name==="this" ))
The some()
method tests whether at least one element in the array passes the test implemented by the provided function. some()
方法测试数组中是否至少有一个元素通过提供的 function 实现的测试。
if you want a returned array of values that match = >如果你想要一个返回的值数组匹配=>
const filtered = arr2.filter((item)=>item.name == 'value')
if you want bool(true||false) =>如果你想要 bool(true||false) =>
const filtered = arr2.filter((item)=>item.name == 'value').length > 0
or using some as mentioned above.或使用上面提到的一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.