[英]Check if a value exists in an Array object in JavaScript or Angular
我想检查数组对象中是否存在值。 例子:
我有这个数组:
[
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
]
我想检查这里是否存在id = 2
。
你可以使用Array.prototype.some
var a = [ {id: 1, name: 'foo'}, {id: 2, name: 'bar'}, {id: 3, name: 'test'} ]; var isPresent = a.some(function(el){ return el.id === 2}); console.log(isPresent);
您可以使用some() 。
如果您只想检查某个值是否存在,那么Array.some()
方法(自 JavaScript 1.6 起)就已经足够了。
let a = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
];
let isPresent = a.some(function(el){ return el.id === 2});
console.log(isPresent);
此外, find()是一个可能的选择。
如果您想获取某个键具有特定值的整个第一个对象,最好使用自 ES6 以来就存在的Array.find()
方法。
let hasPresentOn = a.find(
function(el) {
return el.id === 2
}
);
console.log(hasPresentOn);
您可以使用find方法,如下所示:
var x=[ {id: 1, name: 'foo'}, {id: 2, name: 'bar'}, {id: 3, name: 'test'} ] var target=x.find(temp=>temp.id==2) if(target) console.log(target) else console.log("doesn't exists")
试试这个:
let idx = array.findIndex(elem => elem.id === 2)
if (idx !== -1){
// Your element exists
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.