简体   繁体   中英

Javascript Remove from array if empty

I have an array looking like this:

var testArray = [
    {"cid": "1234567"},
    {"cid": "892345"},
    {"cid": ""},
    {"cid": "8267783"},
    {},
    {"cid": "096873"},
];

How do I remove, either before a for loop or when looping, where cid = "" and where is empty {}

I tried this:

for(var i = 0; testArray.length; i++){

    if(testArray.cid && testArray.cid != ""){

    }

}

This didn't work :-/ Got this error: Cannot read property "cid" from undefined

Hope this makes sense and thanks in advance :-)

Use filter() to filter out undesired data.

 var testArray = [ {"cid": "1234567"}, {"cid": "892345"}, {"cid": ""}, {"cid": "8267783"}, {}, {"cid": "096873"}, ]; console.log(testArray.filter(arr => arr.cid)) 

If you need to remove ALL empty values ("", null, undefined and 0):

arr = arr.filter(function(e){return e}); 

To remove empty values and Line breaks:

arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});

Example

arr = ["hello","",null,undefined,1,100," "]  
arr.filter(function(e){return e});

return

["hello", 1, 100, " "]

When you will use splice() during the loop. You need to decrease i by 1 A better way of doing this using filter() . Below I showed both methods.
And for checking empty object {} you should compare Object.key(obj).length with 0

 var testArray = [ {"cid": "1234567"}, {"cid": "892345"}, {"cid": ""}, {"cid": "8267783"}, {}, {"cid": "096873"}, ]; //doesnot mutates the original array. let result = testArray.filter(x => Object.keys(x).length !== 0 && x.cid !== ''); //original array will be change after this loop for(let i = 0;i<testArray.length;i++){ if(Object.keys(testArray[i]).length ===0 || testArray[i].cid === ''){ testArray.splice(i,1); i--; } } console.log(testArray) console.log(result); 

 var testArray = [ {"cid": "1234567"}, {"cid": "892345"}, {"cid": ""}, {"cid": "8267783"}, {}, {"cid": "096873"}, ]; testArray = testArray.filter(item=> Object.keys(item).length && item["cid"]); console.log(testArray) 

Just added a post filter function for completeness.Vote for HolyDragon tho.

 var testArray = [ {"cid": "1234567"}, {"cid": "892345"}, {"cid": ""}, {"cid": "8267783"}, {}, {"cid": "096873"}, ]; testArray.filter(i => i.cid) .forEach(elem => { // do my code post filter console.log(elem.cid); }); 

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