简体   繁体   中英

Loop through array and return value that is matched

I would like to find a solution that returns the following result when any of the property "value" is true.

This is what I have tried so far, but so far it has not worked

public displayCondition(data:any){
const items = data.status.map((status: { value: boolean; }) =>{
  staus.value === true;
})
return items;

}

Input

const data: [
      {
        name: "php",
        status: [
          {
            value: "true"
          },
          {
            value: "false"
          }
        ]
      },
      {
        name: "java",
        status: [
          {
            value: "false"
          },
          {
            value: "false"
          }
        ]
      }
    ]

Output

[
  {
    name: "php",
    status: [
      {
        value: "true"
      },
      {
        value: "false"
      }
    ]
  }
]

Your data structure has an antipattern: using strings "true" and "false" as booleans true and false . I suggest converting it to real booleans unless you have a very compelling reason to do otherwise. It should be possible to say if (data[0].status[0]) {...} but that's an always-true condition when you use strings.

In your original code, the condition staus.value === true; is always false as it compares a string with a boolean.

Here's how to make the conversion:

 const data = [ { name: "php", status: [ {value: "true"}, {value: "false"} ] }, { name: "java", status: [ {value: "false"}, {value: "false"} ] } ]; data.forEach(e => e.status.forEach(e => { e.value = e.value === "true"; })); console.log(data);

Back to the main problem. map isn't used to search an array; it's used to apply a transformation on each entry in an array.

Try .filter (return all elements matching a predicate) and .some (return true if the predicate is true for any item in an array, otherwise false):

 const data = [ { name: "php", status: [ {value: "true"}, {value: "false"} ] }, { name: "java", status: [ {value: "false"}, {value: "false"} ] } ]; const result = data.filter(e => e.status.some(e => e.value === "true")); console.log(result); // or if you made the boolean conversion: //const result = data.filter(e => e.status.some(e => e.value));

Use .find rather than .filter if you want only the first item that matches the predicate (or null if none matched).

You can use the Array#filter and Array#some methods and object destructuring as follows:

 const data = [ { name: "php", status: [ { value: "true" }, { value: "false" } ] }, { name: "java", status: [ { value: "false" }, { value: "false" } ] } ], output = data.filter( ({status}) => status.some( ({value}) => value === "true" ) ); console.log( output );

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