Aniruddh Bhagwat Aniruddh Bhagwat - 7 months ago 28
Javascript Question

underscore.js no data outside _.each

I'm retrieving a JSONp file with jQuery's $.ajax. I can't figure out how to make the underscore loop work...

in success I've this this code:

success : function(response) {

var dataResp = '';
_.each(response.results, function(response, index) {

var dataResp = response;

var prodName = dataResp.trackName;
var prodUri = dataResp.trackViewUrl;
var prodUri = dataResp.trackViewUrl;
var prodUri = dataResp.trackViewUrl;
var prodPrice = Math.round(dataResp.trackPrice);
var prodImg = dataResp.artworkUrl100.replace("100x100bb.", "700x700bb.");

console.log(prodName); // returns all product names, and that's fine

}, this);

console.log(dataResp); // dataResp is empty


var html = "";
var compiled = _.template($("#product-structure").html(), dataResp );

_.each(dataResp, function(data) { // loop to compile template for all the elements inside the jsonp response
html += compiled(data);
});

$('#data').html(html); // append to html the compiled template


}


I use underscore.js for the templating part but I can't figure out why my data isn't available outside that _.each loop...

here my template:

<script type="text/template" id="product-structure">
<%= data.img %>
<%= data.title %>
<%= data.price %>
<%= data.uri %>
</script>

Answer

you can use the _.map function which returns a new array. I am assuming you want an object returned with those values.

This code will return an array of objects, each object will contain the prodName, prodUri, prodPrice, and prodImg.

var dataResp = _.map(response.results, function(response, index) {
    return {
        prodName: response.trackName,
        prodUri: response.trackViewUrl,
        prodPrice: Math.round( response.trackPrice ),
        prodImg: response.artworkUrl100.replace( "100x100bb.", "700x700bb")
    };
}, this);