map函数返回带undefined的数组如何处理

3,603 阅读1分钟

map函数返回一个数组,并且也传入的数组长度一致,如果没有返回确定的值,就会返回一个undefined,如下例子:

const arr = [{ id: 12, text: "哈密瓜" }, { id: 96, text: '葡萄' }, 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: '哈密瓜' }, {value: 96, label: '葡萄' }, undefined]

此时arr中的第第三个元素为5,没有给定返回值,故返回undefined,如果业务场景需要过滤掉undefined,使用filter方法会更简洁,将getOptions方法改写为:

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

执行结果为[ { id: 12, text: '哈密瓜' }, { id: 96, text: '葡萄' } ] 然而filter无法对返回的json的key进行改写,如果需要将返回值改写成{ value: item.id, label: item.text }这种格式,使用forEach会比较简洁

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

尝试使用reduce来处理,但是玩不转,代码并不是那么简洁直观,记录下来纯单学习。

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 } : []);
        }
    })
}