How to iterate an array and acces a map using Handlebars? - javascript

I have data structures similar to the code below that I want to iterate through with Handlerbars. While the javascript code that can do this iteration is clear, I have not been able to figure out how to do it in handlebars.
var keys = ['key1','key2','key3']
var map = {'key1':{...}, 'key2':{...}, 'key3':{...}, .... 'keyN': {...}}
What I want to do within handlebars is to iterate the keys array and use the value from the keys array to look-up the object from the map. Can this be done without writing a helper?
UPDATE I know how to write the code in javascript, I want to do is "what i can do in raw js using handlebarJS expressions".

try this :
for(var i=0; i<keys.length; i++){
console.log(map[keys[i]])
}
Handlebars.registerHelper('list', function(keys, maps) {
var out = "<ul>";
for(var i=0, i=keys.length; i++) {
out = out + "<li>" + map[keys[i]] + "</li>";
}
return out + "</ul>";
});

Related

convert a html table to a 2D array with numbers with javascript

I use the below JavaScript function to generate a html table from a 2D data array with numbers called d.
function matrix(d) {
var html = '<table>';
for (var i = 0; i < d.length; i++) {
html += '<tr>';
for (var j = 0; j < d[i].length; j++) {
html += '<td>' + d[i][j] + '</td>';
}
html += "</tr>";
}
return html;
}
That function works well but I can only look at the pretty html output and not use the data in other functions so now I am trying to write another function that goes in the opposite direction and converts a html table to a 2D array with numbers. So far I got the below function:
function tableToArray(w) {
var myTableArray = [];
$(w).each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
console.log(myTableArray);
return myTableArray;
}
but that function is not working very well. If I call tableToArray(matrix([[1,2,3],[4,5,6]])) the result in the console.log is a 1D column array with strings (or maybe a 1D row array with string hard to tell the difference in the console log) that looks like "1","2","3","4","5","6". I want a 2D array with numbers and not strings since my original array was a 2D array with numbers. What JavaScript function code will give me that 2D array with numbers?
Assigning the data array d to a global variable (without var) or a window.variable is not an option because I need to be able to call the function likes this: tableToArray(matrix([[1,2,3],[4,5,6]])).
I have googled around all day to find a previous written function that does this but I have not managed to find a working one nor have I been successful in writing one myself.

Split json data using comma

I have a json which has a key "tag", which is returning data like this
"tags": "jname,gender,city"
but i want to append these value in separate span like below
<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>
I am trying with this
$.getJSON("data.json", function(tagsposts) {
var items = [];
splitsVal = tag.split(",");
for (var i = 0; i < splitsVal.length; i++) {
obj.push({name:splitsVal[i]});
obj[i] = '<span>' + obj[i] + '</span>';
$('.tags-div').append(obj[i])
}
$.each(tagsposts, function(key, val) {
items.push('' + val['tags'] + '');
});
$('#tagsposts').append(items.join(""));
});
Am I doing correct
You're trying to split an undefined variable:
function(tagsposts) {
var items = [];
splitsVal = tag.split(","); // but tag doesn't exist...
(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)
Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form
{"tag": "foo,bar,baz"}
then you would want
splitsVal = tagsposts.tag.split(",")
If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.
There are lots of other problems here, however.
You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:
for (var i = 0; i < splitsVal.length; i++) {
$('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}
And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

How to find JSON data at specific index

I want to show only the country name like India,Srilanka etc.
{"result":1,"countries":[
{"country_id":"1","country_name":"Afghanistan"},
{"country_id":"2","country_name":"Albania"},
{"country_id":"3","country_name":"Algeria"},
{"country_id":"4","country_name":"American Samoa"},
{"country_id":"5","country_name":"Andorra"},
{"country_id":"6","country_name":"Angola"},
{"country_id":"7","country_name":"Anguilla"}
]
}
Below I have created JSON object same as yours:
var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';
var obj = JSON.parse(text);
you can loop through JSON object and get each property value as below:
for(i = 0; i < obj.countries.length ; i++)
{
console.log(obj.countries[i].country_name);
}
Hope This Will Help!
why no iterate the objects and pull that data into a separate array? for example:
[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
console.log(element.country_name);
});

concatenate an increment counter onto the end of an array selector within a json response loop

so I'm looping through a json response and I'm trying to use the counter (var i) to say data.newarray[i].time+i so with each loop the next array is chosen and the time also increases in number. So 1st loop will spit out data.newarray[0].time0 then data.newarray[1].time1 then data.newarray[2].time2 and so on. The bit that is currently failing is my concatenation time+i at the end. How do I format this to work?
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i].time+i);
}
You can access variable property names by using the quoted notation: obj['prop'] instead of obj.prop.
The solution is:
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i]['time'+i]);
}
Try something like this:
for(var i=0; i<data.newarray.length; i++) {
alert(data.newarray[i]['time'+i]);
}

how do I name objects dynamically and use object constructor in javascript?

I'm pulling data with Ajax that changes every day. I want to package the data into objects that have unique names. Currently I created a constructor that looks like something like this:
function myObject(Id,thing1,thing2,thing3)
{
this.Id = Id;
this.thing1 = thing1;
this.thing2 = thing2;
this.thing3 = thing3;
}
then I push that to an array in a loop like this
for(var i=0; i<data.length; i++)
{
array.push(new myObject(value1,value2,value3,value4));
}
This works fine for what I'm doing but I just get an array with [object,object,object,object] inside of it which I can access with array[0] , array[1], etc.
but now I want to store those objects in firebase and would need to reference them so how could I have them named uniquely?
normally you would do
var thingid1 = new myObject(value1,value2,value3,value4));
var thingid2 = new myObject(value1,value2,value3,value4));
but this is all being created on the fly and sometimes there is 1 object created and sometimes 10.
I'm new at this and I've looked everywhere so any help would be appreciated.
If your Id (value1) is unique...
var myObjectContainer = {};
for(var i=0; i<data.length; i += 1)
{
myObjectContainer[value1] = new MyObject(value1,value2,value3,value4);
}

Categories

Resources