What am I receiving undefined when building this string? Javascript - javascript

I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!

Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"

You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));

Related

mongodb batch insert - Javascript not working

I want to insert bunch of records into a collection, but instead of document at a time I want to do it like a batch using "insertMany()". I wrote the script as follows:
var batch = [];
for (i=0; i<10; i++) {
names=["exam", "essay", "quiz"];
for (j=0;j<3;j++) {
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
if (mod i%3 == 0) {
batch = batch.slice(0, batch.lenght(-1));
db.scores.insertMany( batch )
batch=[];
}
}
}
The above code is not working. There are two issues: first, the array item have double quotes around them and second, the "slice" is not taking effect.
Need help in fixing the Javascript.
There are a couple of issues here:
the array item have double quotes around them
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
You want to create an object rather than a string. batch = { student: i, type: names[j], score: ..} will create an object for you.
the "slice" is not taking effect
batch = batch.slice(0, batch.lenght(-1));
You've misspelled length, and length is a property rather than a function. batch.slice() will copy the array (but you're resetting it so it's not actually necessary).

Shorthand for "console.log("var: " + var)"?

It would be nice to have a super quick way to do this:
"console.log("var: " + var)"?
Tried this, but not sure if there's a way to get a variable name as a string once it's been passed in, or convert the name string to a reference to the variable...
var mLog = function(varNameStr){
console.log(varNameStr + ": " + _____);
}
EDIT: Judging by the results of googling "get name string of a variable js", it looks like there's no easy way to grab the name string of a variable from the reference (You have to create hash tables or other structures that make it not worthwhile.)
So, the only possible solution would be to convert a string into a reference to the variable. Is that possible in JS?
The following will do the trick. Pass it a variable name in string form.
var mLog = function(varStr){
console.log(varStr + ": " + eval(varStr));
}
Example:
> var strVar = 'A string variable';
> mLog('strVar');
< strVar: A string variable
> var arrVar = [1,2,3];
> mLog('arrVar');
< arrVar: 1,2,3
There is no way to "extract" the variable name, since variables aren't actually data. The closest thing you could do is use it for objects. Something like:
var obj= {
prop: 'value'
};
function mLog(object, prop) {
console.log(prop + ': ' + object[prop];
}
mLog(obj, 'prop');

Getting NaN Error and undefined Error

I have a Problem with my push function in JavaScript.
<script type="text/javascript">
var myArr = []
var len = myArr.length
$.getJSON('daten.json', function(data) {
$.each(data,function(key,value) {
for(var i = 0; i <= len; i++){
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
}
})
$('.content').html(myArr.join(''))
})
</script>
I need to convert value.Name+i like this = value.Name0, value.Name1 and so on. I got a JSON File and the Keys are Dynamic, so the first entry got Name0 the second Name1 and so on. Now I must print the JSON file on my html page, but how I can write this line:
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
with my var i which increment in the loop, to call the Keys in my JSON file?
Like value.Name0. Doing value.Name+i and value.Name.i does not work.
It seems to me what you're looking for is something like this:
myArr.push("<p>" + value['Name'+i] ," ", value['Nachname'+i] + "</p>")
This portion of javascript is covered pretty nicely here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Take the object property in a variable, use condition to check if it has value or not then concat it
var nameval = value.name;
then use in your javascript variable
nameval+i
You need to convert your i (integer value) to string prior to adding it.
use:
value.Name + i.toString()
here's the jfiddle link: http://jsfiddle.net/kpqmp49o/

Removing quotes from a string / an alternative to string

I have dropDown element which takes the options in the format
ctrlOptions:{0:'String',1:'int'}
in addition to simple data types i have user defined data types hence i want to populate this dynamicaly . so i used a loop and concatenation
var dropDown = "{"
for(var i=0;i<dataTypesList.length;i++){
if(i == dataTypesList.length-1){
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name + "'}";
}else{
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name+ "'" + ",";
}}
This yields be the options in required format but along with quotes around it like
ctrlOptions:"{0:'String',1:'int'}"
i want to remove the double quotes i tried with replace it diesnt seem to help. how can i achieve this can i use any other way.
What you want to create is an object & not a string.
So wildly guessing from your code, that the input dataTypesList looks something like this:
dataTypesList = [{Name:'String'}, {Name:'int'}]
You should use :
var dropDown = {};
for(var i=0;i<dataTypesList.length;i++)
dropDown[i] = dataTypesList[i].Name;
And then Output is an object :
{0: "String", 1: "int"}
you can use JSON.parse to convert the options string from string json to object json:
Using your code (slightly modified):
var dropDown = "{"
for(var i = 0; i < dataTypesList.length; i++)
{
if(i === dataTypesList.length - 1)
{
dropDown += i + ":'" + dataTypesList[i].Name + "'}";
}
else
{
dropDown += i + ":'" + dataTypesList[i].Name + "',";
}
}
// later...
ctrlOptions: JSON.parse(dropDown);
Verify your target browsers are compatible: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If not, there are some libraries compatible with older browsers that do the same thing. JSON2 is recommended by the author for out-of-date browsers: https://github.com/douglascrockford/JSON-js

Represent a query string in JSON

I have this Javascript data:
[{id:123,type:"test"},{id:154,type:"another"}]
How would you transform that into something so that I can pass it as a HTTP post request?
menu[0][id] = 123
menu[0][type] = test
menu[1][id] = 154
menu[1][type] = another
I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
EDIT
Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?
this.serialize = function(elem) {
var childs = elem.childElements();
var str = "";
for(var i=0, item; i<childs.length; i++) {
item = childs[i];
str += ((i)?"&":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,"");
str += "&menu[" + i +"][type]=" + item.className;
str += "&menu[" + i +"][section]=" + elem.id;
str += "&menu[" + i +"][position]=" + i;
}
return str;
}
var data = [{id:123,type:"test"},{id:154,type:"another"}];
var params = new Array();
for(var x = 0; x < data.length; x++) {
params.push("id=[" + x + "]=" + escape(data[x].id));
params.push("type=[" + x + "]=" + escape(data[x].type));
}
alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&type=[1]=another
Is that what you want?
menu0.id=123&menu0.type=test&menu1.id=154&menu1.type=another
This is fairly easy to parse on the server, in that it's a regular format.
I believe HTTP POST only accepts a flat key/value collection, not any arbitrary JavaScript data structure.
If you can flatten it (for example, like John Stauffer shows), and if you're posting to your own domain, you can use an XMLHttpRequest to post and pass the key/value collection, formatted like a query string, with the .send(data) method.
If you don't want to implement it yourself most JavaScript libraries should have an implementation (e.g. jQuery.post).
"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")

Categories

Resources