简体   繁体   中英

How can I filter the result of a ternary that's inside a map?

I'm 100000% new to the ternary world, so I really don't understand what's going on. I have the following:

categories.forEach((category) => {   
  const errorCategory = {
    [category]: response.map(
      (r) => r.ds_category === category && r.ds_name
    ),   
   };

  errors = { ...errors, ...errorCategory };
});

I want to filter the r.ds_name to remove all "false" results, how could I do this? I tried:

  1. Doing the filter straight away (r.ds_name.filter(blablabla)) but I get a "this is not a function" error.

  2. Switching from ternary to the old school function, and didn't get any results either.

  3. Filtering errorCategory (errorCategory = errorCategory.filter((item) => item === "false"), but I also got the "this is not a function" error.

Thanks :(

You can use ternary operator in a filter method like this

const newArray = array.filter( element => {
  element.property === "text" ? true : false
})

It check for element.property is equal to "text". If it is equal it returns true. If not returns false. But you dont need to do that. You can simply do this

const newArray = array.filter( element => {
  element.property === "text"
})

This would return the same result

To filter an array, I'd recommend using '.filter' instead of '.map'. This will remove the elements which do not match the requirement set. Assuming response is an object which is an array, or other object which implements 'filter', you can do the following (note the extra brackets):

categories.forEach( ( category ) => {   
    const errorCategory = {
      [ category ]: response.filter(
        (r) => (r.ds_category === category && r.ds_name)
      ),   
    };
    //Do stuff
}

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