Reputation: 2223
I have an array of arrays that I am trying to pull values from. The problem is that I get an undefined error when it hits an empty array.
Here is the array I'm working with:
data = [[Object { myvar=null}], [Object { myvar="testval"}], [], [], []]
Here is the javascript I'm using to get all myvar values:
myarr = [];
for (var i = 0; i < data.length; i++) {
console.log(data[i][0].myvar);
if (data[i][0].myvar) {
dep = data[i][0].myvar;
if (dep != null) {
myarr.push(dep);
}
}
}
The console.log looks like:
null
testval
Error: data[i][0] is undefined
So it breaks when it reaches the first []. How could I remove all the empty arrays before the for loop? Or have the for loop not die when it hits an empty array? Any help appreciated. Thanks.
Upvotes: 1
Views: 161
Reputation: 18097
This is the best and cleanest way to do it.
data.forEach(function(e){
if(Object.keys(e).length) myarr.push(e);
});
take a look http://jsfiddle.net/8zfZd/ open console to see object.
to make it even shorter...
data.forEach(function(e){ (e[0]) && myarr.push(e); });
Upvotes: 0
Reputation: 3269
for (var i = 0; i < data.length; i++) {
if (data[i].length !== 0) continue;
if (data[i][0].myvar) {
dep = data[i][0].myvar;
if (dep != null) {
myarr.push(dep);
}
}
}
Upvotes: 0
Reputation: 99224
You need to make sure data[i] is an array and it has at least 1 item first :
var i, item, myarr = [],
isNotEmptyArray = function(a) {
return Object.prototype.toString.call(a) === '[object Array]' && a.length > 0;
};
for (i = 0; i < data.length; i++) {
item = data[i];
if (isNotEmptyArray(item) && item[0].myvar) {
console.log(item[0].myvar);
dep = item[0].myvar;
if (dep != null) {
myarr.push(dep);
}
}
}
Upvotes: 0
Reputation: 1149
Just wanted to add this as an answer.. In javascript, I believe null == false
. So you can also do something like this:
if(data[i][0])
//it's not null or undefined, do some work
Upvotes: 0
Reputation: 3361
Add this loop before your loop to clear the empty arrays:
var i = 0;
while (true) {
if (i == data.length)
break;
if (data[i].length == 0)
data.splice(i, 1);
else
++i;
}
Upvotes: -1
Reputation: 887385
You can simply check whether the current item is empty:
if (data[i].length === 0) continue;
Upvotes: 3