javascript - Error calling forEach on array -


i getting problem foreach within anoter foreach function:

the results variable contains object like:

{     names: [         'someone',         'someone else'     ],     emails: [         'someone@someemail.com'         'something@somemail.com'     ] } 

i want unwind arrays , result in array this:

[     {term: 'someone', type: 'names'},     ... ] 

here code:

var keys = _.keys(results);  console.log(keys);  var finalresult = [];  keys.foreach( function (key) {      var arrterms = results[key];      console.log(key, arrterms); //arrterms prints fine      arrterms.foreach(function (term) { //this line throws exception          finalresult.push({             term: term,             type: key         });     });  }); 

the nested call foreach throws following exception:

typeerror: uncaught error: cannot call method 'foreach' of undefined 

i tried using loop iteration till length, generated exception:

typeerror: uncaught error: cannot read property 'length' of undefined 

i think problem here may assign undefined arrterms (when results[key] returns undefined cause take key isn't contained in object). try this:

var keys = _.keys(results);  console.log(keys);  var finalresult = [];  keys.foreach( function (key) {     if(results[key] != undefined){      var arrterms = results[key];       arrterms.foreach(function (term) { //this line throws exception         console.log(key, arrterms); //arrterms prints fine         finalresult.push({             term: term,             type: key         });      });     } }); 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -