Search code examples
jqueryarraysvariableseachsub-array

storing $.each() value in variable and using it


I have a sub array, and I am trying to store the results of the sub array like this inside a variable.

$.each(abc[0].Phone, function (i, item) {
   var number = '<p> '+ item.Phone +'</p>';
 }); 

Then I am trying to use this variable inside another variable

var temp = '<div class="row">\n\
              <div class="col-md-6">\n\
                <h4>' + abc[0].FullName + '</h4>\n\
                  <p>Phone: '+ number +' </p>\n\
               </div>\n\
             </div>';

I get the error that number is not declared


Solution

  • Scope Problem and bind outside the loop .

       var number = '';
        $.each(abc[0].Phone, function (i, item) {
            number += '<p> '+ item.Phone +'</p>'; // For repeated  phone
         }); 
    

    And use of number.

    var temp = '<div class="row">\n\
                  <div class="col-md-6">\n\
                    <h4>' + abc[0].FullName + '</h4>\n\
                      <p>Phone: '+ number +' </p>\n\
                   </div>\n\
                 </div>';