简体   繁体   中英

map return undefined array of object?

const newDate = map(items.result, (obj => {
  if (isDateWithinRage(obj.date_from)) {
    return {
      "date": obj.join_date,
      "name": obj.student.name
    }
  }
}))

The if statement has produced something like this

[Object, Object, Object, Object, Object, undefined, undefined, undefined, undefined, Object, Object, Object]

How to fix the undefined part? I want to skip the iteration.

Assuming map is some variant of Array.prototype.map , map produces a 1:1 mapping of values from your input array to an output array.

When you want to exclude values from your input array, use Array.prototype.filter :

const newDate =
  items
    .result
    .filter(obj => isDateWithinRange(obj.date_from))
    .map(obj => ({
      date: obj.join_date,
      name: obj.student.name
    }));

This example assumes that items.result is an Array

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