Check if value exists in Array object Javascript or Angular

后端 未结 4 951
粉色の甜心
粉色の甜心 2021-01-06 15:43

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, nam         


        
相关标签:
4条回答
  • 2021-01-06 16:04

    You can use find method as below

    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")

    0 讨论(0)
  • 2021-01-06 16:18

    You can use 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);

    0 讨论(0)
  • 2021-01-06 16:19

    try this

    let idx = array.findIndex(elem => {
                    return elem.id === 2
                })
    if (idx !== -1){
        //your element exist
    }
    
    0 讨论(0)
  • 2021-01-06 16:20

    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.

    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.

    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.

    let hasPresentOn = a.find(
      function(el) {
      return el.id === 2
      }
    );
    console.log(hasPresentOn);
    
    0 讨论(0)
提交回复
热议问题