检查数组对象 Javascript 或 Angular 中是否存在值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47354589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:19:23  来源:igfitidea点击:

Check if value exists in Array object Javascript or Angular

javascriptangular

提问by Stiven Castillo

I want to check if value exist in array object, example:

我想检查数组对象中是否存在值,例如:

I have this array:

我有这个数组:

[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]

And I want check if id = 2exist here.

我想检查id = 2这里是否存在。

Thanks

谢谢

回答by Karim

You can use Array.prototype.some

你可以使用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);

回答by Chang

You can use: some()

您可以使用:一些()

If you want to just check whether a certain value exists or not, Array.some()method (since JavaScript 1.6)is fair enough as already mentioned.

如果你只想检查某个值是否存在,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);

Also, find()is a possible choice.

此外,find()是一个可能的选择。

If you want to fetch the entire very first object whose certain key has a specific value, better to use Array.find()method which has been introduced since ES6.

如果您想获取某个键具有特定值的整个第一个对象,最好使用Array.find()自 ES6 以来引入的方法。

let hasPresentOn = a.find(
  function(el) {
  return el.id === 2
  }
);
console.log(hasPresentOn);

回答by sumeet kumar

You can use find method as below

您可以使用 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")

回答by Fateh Mohamed

try this

试试这个

let idx = array.findIndex(elem => {
                return elem.id === 2
            })
if (idx !== -1){
    //your element exist
}