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 :-)
5 Answers 5
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))
3 Comments
cid will be true,0,undefined,null. And OP only asked for ''filter() using simple loopsIf 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, " "]
Comments
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);
Comments
var testArray = [
{"cid": "1234567"},
{"cid": "892345"},
{"cid": ""},
{"cid": "8267783"},
{},
{"cid": "096873"},
];
testArray = testArray.filter(item=> Object.keys(item).length && item["cid"]);
console.log(testArray)
Comments
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);
});
indexof itemif( testArray[i].cid )