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, " "]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With