Home > Back-end >  How to use the map function with conditional logic
How to use the map function with conditional logic

Time:07-01

In the following code, components is an array of objects containing these values: {name: '', url: '', type: '', show: 1}

1 render() {
2   return (
3                   ...
4                   {this.state.editableRowData.components.map((c, i) => (
5                       <>
6                   ...
7   );
8 }

How do I conditionally map components to UI inside of the map function based on if the show value is 1?

CodePudding user response:

You can filter them before mapping through the list.

this.state.editableRowData.components.filter(item => item.show === 1).map((c, i) => (...rendering logic))

CodePudding user response:

basically you do not need map, because map creates an array of exact same size of the original array, what you need is filter, which behaves almost the same as map but it filters what you do not want to be on the array, therefore you could have something like:

this.state.editableRowData.components.filter((c, i) => (c.show === 1));

working code with difference between map and filter

const array = [{
    "name": 0,
    "url": 0,
    "type": 0,
    "show": 1
  },
  {
    "name": 1,
    "url": 1,
    "type": 1,
    "show": 0
  },
  {
    "name": 2,
    "url": 2,
    "type": 2,
    "show": 1
  },
  {
    "name": 3,
    "url": 3,
    "type": 3,
    "show": 0
  },
  {
    "name": 4,
    "url": 4,
    "type": 4,
    "show": 1
  }
]


const result = array.filter((item) => item.show === 1);
const resultMap = array.map((item) => (item.show === 1? item: null));

console.log(result)
console.log("------------------")
console.log(resultMap);

  • Related