Tom Rudge
Tom Rudge

Reputation: 3272

How to not map object that has a child value missing

I am mapping some data in array. The array length is 3 so I get 3 versions. If a child value is '' or undefined I don't want it to map that object at all just the ones that have all values.

const data = {
  status4Weeks: "2",
  status12Weeks: ""
}; 

status12weeks should be skipped as its empty. I create a new array for my mapping adding in some other values.

const newdata = [
      {
        title: "4 Weeks",
        statusWeek: data.status4Weeks,
        color: status4WeeksColor,
        numWeeks: 4
      },
      {
        title: "12 Weeks",
        statusWeek: data.status12Weeks,
        color: status12WeeksColor,
        numWeeks: 12
      }
    ];

4 weeks should not be mapped as the essential value that drives this is missing.

{newdata.map(v => (
            <ListItem dense={this.props.dense} alignItems="flex-start">
              <ListItemText
                primary={
                  <React.Fragment>
                    Predicted score - <strong>{v.title}</strong>
                  </React.Fragment>
                }
                secondary={
                  <React.Fragment>
                    <Typography component="span" color="textPrimary">
                      Predicted date{" "}
                      <i
                        style={{ "font-size": "1em" }}
                        className="zmdi zmdi-calendar mx-2"
                      />{" "}
                      {moment(data.vulnerabilityDate)
                        .add(v.numWeeks, "weeks")
                        .format("MMM DD, YYYY")}
                    </Typography>
                  </React.Fragment>
                }
              />
              <ListItemSecondaryAction>
                <span
                  style={{
                    "font-size": "1rem",
                    "background-color": v.color,
                    "min-width": "45px"
                  }}
                  className="vulnerability badge badge-primary"
                >
                  {v.statusWeek}
                </span>
              </ListItemSecondaryAction>
            </ListItem>
          ))}

Here is a codesandbox - https://codesandbox.io/s/wq72p92295

I've tried using a ternary operator, inside my mapping :

{v.status.Week !== '' || undefined ? ...

Upvotes: 2

Views: 307

Answers (2)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4577

Mapping an array will still return remove an index from an array.

Using filter would work in this case.

You should use something like:

array.filter(e=> (e!==undefined && e.length>0)).map(e=> /*your map stuff*/)

Hope this helps,

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can simply use reduce.

inside reduce you can check for existence of value if it is true than only add to final output.

newdata.reduce((op,inp) => {
  if(inp) {
    op.push(inp)
  }
  return inp
},[])

Upvotes: 1

Related Questions