multi line variable in javascript - javascript

I am trying to make this javascript variable with some data from an array , but i cant figure out the right syntax to make this work..
certifications will be "Win7,Win8,PDI"
var myArray = certifications.split(",");
var data = "[{" +
for (var i in myArray)
" "id":i,"text":myArray[i]}, " +
"}]";
I'm hoping to get my data variable to look something like:
var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";

Try this:
var data = JSON.stringify(certifications.split(",").map(function(value, index) {
return {
id: index,
text: value
};
}));

Maybe += is what your looking for:
var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";
for (var i in myArray) {
data += " " +
"id" +":"+i+","+
"text" + ":"+myArray[i]+"}, ";
}
data += "}]";

Related

Retriving data from firebase web

I am trying to fetch the data for website using java script. Problem I am getting is that I am unable to get the key of Users-->history-->location-->from-->(lat,lng). I am unable to find a syntax of it.
Code I am trying is
var ref = firebase.database().ref("history/" + keys +"/location/from");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
//console.log(data.val());
var from = data.val();
var keys=Object.keys(from);
console.log(keys);
for(var i=0 ; i<keys.length;i++)
{
var k=keys[i];
var name = from[k].customer;
var phone = from[k].driver;
//console.log(name,phone,imag);
$('ul').append( '<li>' + name +" : " + phone+ '</li>' );
}
}
This should print the lat and lng of each item in the history:
var ref = firebase.database().ref("history/");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
data.forEach(function(child) {
var from = data.val().location.from;
console.log(from.lat+","+from.lng);
});
}

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Handlebars confusion I don't get it

I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys
https://codepen.io/blaze4dem/pen/zZmqKa
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options){
var radioList = options.fn();
radioList = radioList.trim().split("\n");
var output = "";
for(var val in radioList){
var item = radioList(val).trim();
output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innaHTML += tempdata;
I see 3 issues in the code.
for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.
You have a typo, when you are replacing the element. Supposed to be innerHTML
radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].
You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options) {
debugger;
var radioList = options.fn();
var hasSpaces = radioList.indexOf(' ') > -1;
var hasNewLines = radioList.indexOf('\n') > -1;
if (hasNewLines) {
radioList = radioList.trim().split("\n");
} else if (hasSpaces) {
radioList = radioList.trim().split(" ");
}
var output = "";
// for in is best to iterate over objects.
// use for loop instead
for (var i = 0; i < radioList.length; i++) {
var item = radioList[i].trim();
output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;
Check Fiddle

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Javascript challenge. How do I achieve this with arrays?

Let's say I have:
var directions = [ "name", "start_address", "end_address", "order_date" ];
I'm trying to find a slick, fast way to turn that array into this:
data: {
"directions[name]" : directions_name.val(),
"directions[start_address]" : directions_start_address.val(),
"directions[end_address]" : directions_end_address.val(),
"directions[order_date]" : directions_order_date.val()
}
Notice the pattern. The name of the array "directions" is the prefix to the values.
I'm interested how people can either do this or at least suggest a way for me to try.
Any tips would be appreciated.
Thanks!
EDIT **
Thanks for the suggestions so far. However, I forgot to mention that the array "directions" needs to be dynamic.
For example, I could use:
places = ["name", "location"]
should return
data: {
"places[name]" : places_name.val(),
"places[location]" : places_location.val()
}
alpha = ["blue", "orange"]
should return
data: {
"alpha[blue]" : alpha_blue.val(),
"alpha[orange]" : alpha_orange.val()
}
So basically I could just pass an array into a function and it return that data object.
var directions = ["name", "start_address", .... ];
var data = someCoolFunction( directions );
Hope that makes sense.
** EDIT **************
I want to thank everyone for their help. I ended up going a different route. After thinking about it, I decided to put some meta information in the HTML form itself. And, I stick to a naming convention. So that an HTML form has the information it needs (WITHOUT being bloated) to tell jQuery where to POST the information. This is what I ended up doing (for those interested):
// addBox
// generic new object box.
function addBox(name, options) {
var self = this;
var title = "Add " + name.charAt(0).toUpperCase() + name.slice(1);
var url = name.match(/s$/) ? name.toLowerCase() : name.toLowerCase() + "s";
allFields.val(""); tips.text("");
$("#dialog-form-" + name).dialog( $.extend(default_dialog_options, {
title: title,
buttons: [
{ // Add Button
text: title,
click: function(){
var bValid = true;
allFields.removeClass( "ui-state-error" );
var data = {};
$("#dialog-form-" + name + " input[type=text]").each(function() { // each is fine for small loops :-)
var stripped_name = this["name"].replace(name + "_", "");
data[name + "[" + stripped_name + "]"] = $("#dialog-form-" + name + " #" + name + "_" + stripped_name).val();
});
// verify required fields are set
$("#dialog-form-" + name + " input[type=text].required").each(function() {
bValid = bValid && checkLength( $(this), $(this).attr("name").replace("_", " "), 3, 64 );
});
// find sliders
$("#dialog-form-" + name + " .slider").each( function() {
data[name + "[" + $(this).attr("data-name") + "]"] = $(this).slider( "option", "value" );
});
data["trip_id"] = trip_id;
if(options != null) { $.extend(data, options); } // add optional key/values
if(bValid) {
$(".ui-button").attr("disabled", true);
$.ajax( { url : "/" + url, type : "POST", data : data } );
}
}
},
{ text: "Cancel", click: function(){$( this ).dialog( "close" );} }
]
}));
}
It's really unclear what you want here. Perhaps you should give the interface to the function you want, and an example of some code which sets up some sample variables and calls the function.
What you seem to be asking for is to dynamically find variables which you have already declared in the environment, such as directions_name and directions_start_address, and call the val() method on each of them, then construct a dictionary mapping strings to those results. But the keys of the dictionary contain JavaScript syntax. Are you sure that's what you want?
function transform(name)
{
var data = {};
var names = window[name];
for (var i=0; i<names.length; i++)
{
data[name + "[" + names[i] + "]"] = window[name + "_" + names[i]].val();
}
return data;
}
Edit: To use JQuery to look up objects by ID instead of the above approach (which looks up global variables by name):
function transform(name)
{
var data = {};
var names = $("#" + name);
for (var i=0; i<names.length; i++)
{
data[name + "[" + names[i] + "]"] = $("#" + name + "_" + names[i]).val();
}
return data;
}
This will look up the name in the global space of the window (which will work in a browser anyway). You call that function with "directions" as the argument. For example:
var directions = [ "name", "start_address", "end_address", "order_date" ];
var directions_name = {"val": function() {return "Joe";}};
var directions_start_address = {"val": function() {return "14 X Street";}};
var directions_end_address = {"val": function() {return "12 Y Street";}};
var directions_order_date = {"val": function() {return "1/2/3";}};
data = transform("directions");
Is that what you want?
(Note: I see someone else posted a solution using $ and "#" ... I think that's JQuery syntax, right? This works without JQuery.)
Edit: Note that this lets you use a dynamic value for "directions". But I'm still not sure why you want those keys to be "directions[name]", "directions[start_address]", instead of "name", "start_address", etc. Much easier to look up.
Edit: I fixed my sample code to use functions in the values. Is this really what you want? It would be easier if you weren't calling val() with parens.
Like this:
var data = { };
for(var i = 0; i < directions.length; i++) {
var name = directions[i];
data["directions[" + name + "]"] = $('#directions_' + name).val();
}
Or,
data["directions[" + name + "]"] = directionsElements[name].val();
EDIT: You can pass an array and a prefix.

Categories

Resources