Home > front end >  How to check if data is exist
How to check if data is exist

Time:10-29

I need to loop thought data and need to check if value. First check my code:

What i need. inside map above i need to set one if and just prop to NewComponent data where if is true? What i try:

but this no work.

CodePudding user response:

It's hard to understand your question, but from what I've understood you want to return a view component if it matches with your preferred condition and another one if it doesn't.

Here's how you should do it

  const childrenComponent = allData.filter(filteredDatas).map((item) => { 

    if (item.name === 'John') {
       return <div key={item.name}>{item.name}</div>
    } 

    return (
      <NewComponent
        key={item.name} 
        age={item.age} 
      />
    );
  });

also make sure that after filtering the item is actually there, you can console log the item above the if condition. Your procedure is okay and should work, if it doesn't check whether it actually returning anything. If it returns a view component, you should see it in the view.

Also, another better approach is to filter the array and store it in a state value and then map it directly inside the div element, if you need to make a large calculation or the code snippet is pretty big for the item, create another component for it and pass the item value to it in the props. This way you can check in every step and find out where you're making mistakes or what's not working.

CodePudding user response:

There are missing some informations on what you want to achieve exactly and what the type of your data is. But if I understand you correctly, you just want a NewComponent if the name differs from John and otherwise nothing?

If so, you can simply filter your data with your desired condition before you map it.

const childrenComponent = allData.filter(filteredDatas).filter(item => item.name !== "John" ).map((item) => { 

  return (
    <NewComponent
      key={item.name} 
      age={item.age} 
    />
  );
});

As you already have a filteredDatas, you can also maybe combine the filters.

  •  Tags:  
  • php
  • Related