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;
2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Updated, you can use some() function:

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

Comments

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'));

Comments

0

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

this.hasAccordionLayout = this.data.find( d => d.type === 'acc-item') != undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.