简体   繁体   中英

how to return an empty array with array.map

I need to return an empty array if obj.chk != true to check if no checked toDos

function listChk() 
{
    if (!chkExist('./toDoArr')) {console.log('Please create toDo list first!')}
    else {

        let toDoArr = JSON.parse(fs.readFileSync('./toDoArr'))

        let chkToDoArr = toDoArr.map(function (obj) {
            if (obj.chk === true){
               console.log( obj.toDo)
               return obj.toDo
            }
        });
        console.log(chkToDoArr) // >>  [ undefined, undefined ]

        if (chkToDoArr.length < 1) 
        console.log('no checked toDos or empty list');
    }
}

thanks

I believe what you need to use is filter instead of map. For example:

let chkToDoArr = toDoArr.filter(function (obj) {
  return obj.chk === true
})

console.log(chkToDoArr) // >>  []

Filter returns an array of results where the comparing function returns a truthy.

 let chkToDoArr = toDoArr.filter(obj => obj.chk).map(obj => obj.toDo)
  1. filter method checks if received elemet prop is true returns that elemen. on the false returns nothing. if on the array all objects element prop(chk) is false returns empty array
  2. second action is map filtered data and return array with toDo prop

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