The map function returns an array of the same length. If no definite value is returned, undefined is returned, as in the following example:

const arr = [{ id: 12.text: "Cantaloupe" }, { id: 96.text: 'grapes' }, 5];
const getOptions = (list) = > {      
     return list.map(item= > {  
         if (item.id && item.text) {  
             return { value: item.id, label: item.text }  
         }  
     });  
 }  
 console.log(getOptions(arr))  //[{value: 12, label: 'cantaloupe'}, {value: 96, label: 'wine'}, undefined]
Copy the code

In this case, the third element in arR is 5 and there is no return value given, so undefined is returned. If business scenarios need to filter out undefined, it is simpler to use the filter method and rewrite the getOptions method as:

    const getOptions = (list) = > {
       if (!Array.isArray(list)) return [];
       return list.filter(item= > item.id && item.text);
      }
Copy the code

[{id: 12, text: ‘cantaloupe’}, {id: 96, text: ‘grape’}] {value: item.id, label: {value: item. The format item.text} is simpler with forEach

const getOptions = (list) = > {
    let arr = [];
    list.forEach(item= > {
        if (item.id && item.text) {
            arr.push({ value: item.id, label: item.text }); }})return arr;
}
Copy the code

Try to use reduce to deal with it, but it doesn’t work. The code is not so simple and intuitive, so it is pure learning to record.

const getOptions = (list) = > {
    return list.reduce((acc, cur, idx) = > {
        if (idx == 1) {
            acc = acc.id ? [{ value: cur.id, label: cur.text }] : [];
            return acc.concat(cur.id ? { value: cur.id, label: cur.text } : []);
        } else {
            return acc.concat(cur.id ? { value: cur.id, label: cur.text } : []); }})}Copy the code