0

I need to check if data is have a type as acc-item, if yes then I need assign a value true or false to this variable hasAccordionLayout.

data = [  
           {  
              type:"text",
              text:"This is just text"
           },
           {  
              type:"acc-item",
              text:"This is acc-item"
           },
           {  
              type:"acc-item",
              text:"This is acc-item 2"
           },
           {  
              type:"text",
              text:"This is just text"
           }
        ];

This is what I tried, But want to do it in a better way

this.hasAccordionLayout = (this.data.filter( function(content) {
            if(data.type === 'acc-item') {
              return data;
            }
          })).length > 0? true: false;
sevic
  • 879
  • 11
  • 36
user007
  • 189
  • 2
  • 13
  • You should check the [some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) Array function – ndoes Jul 18 '19 at 08:30
  • Possible duplicate of [How to determine if Javascript array contains an object with an attribute that equals a given value?](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) – barbsan Jul 18 '19 at 08:43

4 Answers4

3

You can use Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

 this.hasAccordionLayout = data.some(e => e.type === 'acc-item');

See this for live demo.

Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
0

Updated, you can use some() function:

data.some(item => item.type === 'acc-item');
Ethan Vu
  • 2,911
  • 9
  • 25
0

You can use the Array.prototype.find():

this.hasAccordionLayout = this.data.find( d => d.type === 'acc-item') != undefined
Toothgip
  • 469
  • 6
  • 14
0

try with some function like this:

data = [ { type:"text", text:"This is just text" }, { type:"acc-item", text:"This is acc-item" }, { type:"acc-item", text:"This is acc-item 2" }, { type:"text", text:"This is just text" } ];
        
const exist = key => data.some(ele=>ele.type === key);
        
console.log(exist('acc-item'));
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23