简体   繁体   中英

how to use 'includes' correctly in vue

I want to show an error message if object in an array has the string FAILED . My array looks like this:

在此处输入图像描述

And my code to check if one object has state: "FAILED" looks like this:

hasFailedTask() {
  console.log(this.model.status.tasks);
  return this.model.status.tasks.state.includes('FAILED');
},

but then I always get the following error message in my console:

vue.runtime.esm.js:587 [Vue warn]: Error in render: "TypeError: Cannot read property 'includes' of undefined"

Does anyone know the problem and could support me?

Thank you in advance!

You could use find method since this.model.status.tasks is an array:

hasFailedTask() {
 
  return  this.model.status.tasks.find(task=>task.state.includes('FAILED'));
},

your function should look like this:

hasFailedTask() {
  //console.log(this.model.status.tasks);
  return this.model.status.tasks.some(({state}) => state === "FAILED")
},

You can also use flatMap to allow an includes check:

hasFailedTask() {
    return this.model.status.tasks.flatMap(t => t.state).includes('FAILED');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM