Search code examples
javascriptarraysasynchronousrequesthandlebars.js

Storing arrays in data and showing it in handlebars


Need some help in the snippet below. Goal: How to store array in data.nick and show it in handlebars(each separately)?

JS:

function(data, callback){
            var URL = 'url';
            request(URL, function(err, response, body) {
                if(response.statusCode == 200){
                var json = JSON.parse(body);
                    for(var i = 0; i < json['nick'].length; i++){
                        var s = [];
                        s = json['nick'][i].id;
                    }
                    data.nick = s;
                    console.log(data.nick);
                    callback(null,data);
                }
            });
        },

Issue: data.nick is storing only the last object queried while s is an array.


Edit:

Array fixed, the question for now is how to show each of the items in html using express-handlebars

I was trying to use {{#each info.nick}}, {{#list info.nick}}, {{info.nick.[0]}} etc. but it's not working.

I've got array [ 432, 3, 104, 222, 30, 11, 62, 421, 17, 412 ] and I would show each of it using express-handlebars.


Solution

  • You are reseting the array s to be empty on each loop. Along with that you are not adding an item to the array, rather you are overwriting the array with a single value of json['nick'][i].id. That's why you are only seeing the last item, because all the other ones where lost. You will want to define you array before the for-loop and use .push() to add an item to it:

    ...
    var s = [];
    for(var i = 0; i < json['nick'].length; i++){
        s.push(json['nick'][i].id);
    }
    data.nick = s;
    ...
    

    Note that data.nick = s is a shallow copy.