1

I would like ot use conditional inside a filter() function in vuejs, but i got an error after || if

This is my code :

return this.produits.filter((item) => {
  return (
    item.codeproduct == this.codebar ||
    if (item.produitbrand) {
      for (let i = 0; i < item.produitbrand.length; i++) {
        if (item.produitbrand[i].brandsubproduit) {
          for (let e = 0; e < item.produitbrand[i].brandsubproduit[e].length; e++) {
            item.produitbrand[i].brandsubproduit[e].codeproduct == this.codebar
          }
        }
      }
    });
})

Any orientation ? Thank you.

Update : This is my error : Error message

4
  • Post the error. Commented Nov 28, 2019 at 15:16
  • what is the error msg? Commented Nov 28, 2019 at 15:16
  • Thank you for ur reactivity, i updated post for you Commented Nov 28, 2019 at 15:19
  • if is a statement. You cannot use it with || as part of an expression Commented Nov 28, 2019 at 15:37

1 Answer 1

2

if and for statements are not allowed inside an expression.

return ( starts an expression.

If I understand correctly what you are trying to do, this is how you should write it:

return this.produits.filter((item) => {
  if (item.codeproduct == this.codebar) {
    return true;
  } 
  if (item.produitbrand) {
    for (let i = 0; i < item.produitbrand.length; i++) {         
      if (item.produitbrand[i].brandsubproduit) {
        for (let e = 0; e < item.produitbrand[i].brandsubproduit.length; e++) {         
          if (item.produitbrand[i].brandsubproduit[e].codeproduct == this.codebar) {
            return true;
          }
        }
      }
    }
  }
  return false;
});

It is really matter of style, but this is how I would write it:

return this.produits.filter(item => {
  if (item.codeproduct == this.codebar) return true;
  for (let { brandsubproduit } of item.produitbrand || [])
    for (let { codeproduct } of brandsubproduit || [])
      if (codeproduct == this.codebar) return true;
  return false;
});
Sign up to request clarification or add additional context in comments.

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.