How to remove JSON objects that are undefined

I have a Json array loaded in API

I called them with

categories.map((i,j) =>{
  return (<Tab label={'' + i.Name} key={j}/> );
})

It is displayed as Fashion, Health, undefined, undefined, undefined , since the numbers from 141 to 321 are undefined.

How to prevent undefinedfrom printing in response? Thank.

+4
source share
4 answers

You can conditionally return it:

categories.map((i,j) =>{
  return (i.svcName && <Tab label={'' + i.svcName} key={j}/> );
}) 

UPDATE
Reaction example:

const arr = [{
    val: 1
  },
  {
    val: 2
  },
  {
    val: false
  },
  {
    val: ''
  },
  {
    noval: 'blahh'
  },
  {
    val: 3
  },
  {
    val: undefined
  },
  {
    val: 4
  },
]

const Tab = ({ value }) => <div className="tab">{value}</div>;

class App extends React.Component {
  render() {
    return(
      <div>
      {
        arr.map((obj, i) => obj.val && <Tab value={obj.val} key={i} />)
      }
      </div>
    );
  }
}
ReactDOM.render(<App/>, document.getElementById('root'));
.tab{
  height: 50px;
  width: 100px;
  display:inline-block;
  background-color: #333;
  color:#fff;
  text-align:center;
  border: 1px solid #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Run code

CHANGE
As noted @Chris in his reply, my approach eliminates values fakes , such as null, undefined, "", 0, NaN, etc.

+3
source

, undefined :

categories.map((i,j) =>{
  return (i.svcName !== undefined && <Tab label={'' + i.svcName} key={j}/> );
});

, svcName undefined, null, .

, @Sag1v.

+2

If you do not need the result of the map function, for example [el, el, el, false, el, el], you should use the filter earlier:

categories.filter(el => el.svcName !== undefined).map((i,j) =>{
  return (<Tab label={'' + i.svcName} key={j}/> );
})
0
source

C Array#FilterandArray#Map

categories.filter(i => i.svcName !== undefined).map((x,i) => <Tab label={'' + x.svcName} key={i}/>);
0
source

Source: https://habr.com/ru/post/1685227/


All Articles