How to get total number of variables in an array in Javascript? - javascript

Google wasn't my friend on this one... maybe I wasn't searching for the right terms.
I have a javascript array randomTagLine[0], randomTagLine[1], etc. How do I get the total number of variables in the array? For instance, I can physically see there are 23, but I need to pull that out via JS code...
Thanks in advance..
EDIT
Example of code:
var randomTagline = new Array();
randomTagline[0] = "TEXT0";
randomTagline[1] = "TEXT1";
randomTagline[2] = "TEXT2";
//...
randomTagline[23] = "TEXT23";
var randomTaglineLength = randomTagLine.length;
var randomTaglineNum = randomXToY(0,randomTaglineLength,0);
alert(randomTaglineNum + " " + randomTaglineLength);

It's :
var length = randomTagLine.length;

Related

JSON Data to Javascript Array Undefined

I am trying to get data from a JSON file and use Javascript Code to put it into Google Spreadsheet, I did good with some part of the data but I'm stuck with the other part, where I want to match the User Id and put all the data with it on a same row,
JSON Data:
"m":{"414":{"a":{"0":{"c":38,"p":12812.4},
"4":{"c":35,"p":10559.94},"2":{"c":43,"p":35811.63},
"6":{"c":48,"p":45530}},"d":{"0":{"c":55,"p":5477.06225},
"4":{"c":694,"p":106649.473},"2":{"c":1844,"p":716733.50775000011},
"6":{"c":605,"p":324152.5875}},"i":{"0":{"c":0,"p":0},
"4":{"c":0,"p":0},"2":{"c":0,"p":0},"6":{"c":542,"p":19893.93}}},
"404":{"a":{"0":{"c":15,"p":916.182},"4":{"c":50,"p":12357},
"2":{"c":530,"p":390825.27},"6":{"c":58,"p":4841.55}},
"d":{"0":{"c":10,"p":3145.8},"4":{"c":770,"p":141876.12},
"2":{"c":4854,"p":2173966.6125000003},
"6":{"c":1973,"p":1145077.425}},"i":{"0":{"c":0,"p":0},
"4":{"c":0,"p":0},"2":{"c":0,"p":0},"6":{"c":594,"p":25444.41}}}},
Javascript:
var testUF = [];
var Uid = Object.getOwnPropertyNames(doc1.m);
for (var lp2 = 0; lp2 < Uid.length; lp2++) {
var Ua1 = doc1.m[lp2].a["0"].p;
var Ua2 = doc1.m[lp2].a["4"].p;
var Ua3 = doc1.m[lp2].a["2"].p;
var Ua4 = doc1.m[lp2].a["6"].p;
var Ud1 = doc1.m[lp2].d["0"].p;
var Ud2 = doc1.m[lp2].d["4"].p;
var Ud3 = doc1.m[lp2].d["2"].p;
var Ud4 = doc1.m[lp2].d["6"].p;
var Ui4 = doc1.m[lp2].i["6"].p;
testUF.push([Uid,Ua1,Ua2,Ua3,Ua4,Ud1,Ud2,Ud3,Ud4,Ui4]);}
I am getting the Array on the Uid while Debugging, but all the other Variables don't get the data it stays Undefined. I want all the other variables to match with the Uid's and stay in the same row. I did the JSON parsing and everything.
I am asking for the first time on stackoverflow, please forgive me if I couldn't state everything properly. Thank you for the help. :)
You're not using the array index for Uid properly.
Change:
var Ua1 = doc1.m[lp2].a["0"].p;
To:
var Ua1 = doc1.m[Uid[lp2]].a["0"].p;

How do I overwrite object properties in an array?

I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}

Split Javascript String

I've got a javascript string called cookie and it looks like that:
__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en
It could have more ;xxxxxx; but always the entries will be surrounded by ;.
Now i want to split my var into a array and search for the entry "language=xy", this entry should be saved in "newCookie".
Could anyone help me please i'm completly stucked at splitting the var into a array and search for the entry.
Thanks for helping and sharing
var cookie = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;';
var cookie_array = cookie.split(';'); // Create an Array of all cookie values.
// cookie_array[0] = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10'
// cookie_array[1] = '__utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
// cookie_array[2] = '__utmb=43024181.19.10.1349761990'
// cookie_array[3] = '__utmc=43024181'
// cookie_array[4] = 'language=en'
var size = cookie_array.length; // Get Array size to prevent doing lookups in a loop.
for (var i = 0; i < size; i++) {
var keyval = cookie_array[i].split('='); // Split into a key value array
// What we're trying to find now.
// keyval[0] = 'language'
// keyval[1] = 'en'
if (keyval[0] == 'language') { //keyval[0] is left of the '='
//write new cookie value here
console.log('Language is set to ' + keyval[1]); // keyval[1] is right side of '='
}
}
Hope this helps ya out.
For more info on the split() method look at split() Mozilla Developer Network (MDN) documentation
Use a simple regexp for this:
var getLanguage = function(cookie){
var re = new RegExp(/language=([a-zA-Z]+);/);
var m = re.exec(cookie);
return m?m[1]:null;
};
var lang = getLanguage('__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;');
// lang = "en"

Javascript / JQuery comma separated value find last in list and build array

I have a list of options in a select field and each one of these has a comma separated list in the value, I need to loop through these and get the last item in the list and build an array to set into some input fields.
I need to do this in reverse as the ',' separated value I am getting is from a web service which will parse either 5 or 6 items of data which build into an address.
I have started on JSFiddle but I am a bit stuck.
http://jsfiddle.net/justinerswell/feDTU/1/
Any help would be great, I know that this is no the best way of processing data but its all I have to work with.
I have reposted this as it warrants it as the question has evolved.
Thanks
From the question I assume that you are looking to parse the value from either 5 or 6 comma separated value in your option and then separate them into array and want to do something with them (like putting it somewhere else). Below is the modification of your script that I made. I am not getting the question clearly, but I am assuming this is what you want.
$(document).ready(function () {
$('select').click(function () {
var selected = $(this).find(':selected').text();
var substr = selected.split(',');
var country = "";
var postcode = "";
var county = "";
var city = "";
var addthree = "";
var addtwo = "";
var addone = "";
if(substr.length == 5) {
country = substr[4];
postcode = substr[3];
county = substr[2];
city = substr[1];
addone = substr[0];
} else if (substr.length == 6) {
country = substr[5];
postcode = substr[4];
county = substr[3];
city = substr[2];
addtwo = substr[1]
addone = substr[0];
}
// do something here with the array
});
});

Javascript 2-d associative arrays

I have a Javascript 2-D array defined as follows:
proData[prov_999998] = new Array();
proData[prov_999998]["address"] = "29 South St. South #202 Uxbridge ON L9P 1V9";
proData[prov_999998]["phone"] = "555-555-5555";
proData[prov_999998]["fax"] = "444-444-4444";
I'm trying to access these array elements in this function:
function switchPro(value) {
document.getElementById("letterheadName").value = value;
document.getElementById("letterheadAddress").value = providerData[prov_999998]["address"];
document.getElementById("letterheadAddressSpan").innerHTML = providerData[prov_999998]["address"] ;
document.getElementById("letterheadPhone").value = providerData[prov_999998]["phone"];
document.getElementById("letterheadPhoneSpan").innerHTML = providerData[prov_999998]["phone"];
document.getElementById("letterheadFax").value = providerData[prov_999998]["fax"];
document.getElementById("letterheadFaxSpan").innerHTML = providerData[prov_999998]["fax"];
}
But I'm getting an error saying: "prov_999998 is undefined in "providerData[prov_999998]["address"];".
Can someone please help me with this? I can't have numbers as array indexes because javascript does not accept array index starting with '0' such as [0999]. These array indexes are Ids entered by the user and I can't put a restriction on the Id format. I am new to javascript so I'd appreciate any help.
Actually, I want the 1st index to be a variable. This is what I was doing:
function switchProvider(value) {
var val = "prov_"+value;
document.getElementById("letterheadName").value = value;
document.getElementById("letterheadAddress").value = providerData[val]["address"];
document.getElementById("letterheadAddressSpan").innerHTML = providerData[val]["address"] ;
document.getElementById("letterheadPhone").value = providerData[val]["phone"];
document.getElementById("letterheadPhoneSpan").innerHTML = providerData[val]["phone"];
document.getElementById("letterheadFax").value = providerData[val]["fax"];
document.getElementById("letterheadFaxSpan").innerHTML = providerData[val]["fax"];
}
But this is not working, the values on the webpage are being rendered as 'undefined'. What am I doing wrong?
Here's more code, it's JSP and Javascript together.
var providerData = new Array();
<%
for (Provider p : prList) {
if (!p.getProviderNo().equalsIgnoreCase("-1")) {
String prov_no = "prov_"+p.getProviderNo();
%>
providerData[<%=prov_no%>]["address"] = "<%=(p.getClinicAddress() + " " + p.getClinicCity() + " " + p.getClinicProvince() + " " + p.getClinicPostal()).trim() %>";
providerData[<%=prov_no%>]["phone"] = "<%=p.getClinicPhone().trim() %>";
providerData[<%=prov_no%>]["fax"] = "<%=p.getClinicFax().trim() %>";
<% }
} %>
The syntax you use is for object key/value pairs, and not for arrays.
You should most likely use
var proData = {};
proData['prov_999998'] = {};
proData['prov_999998']["address"] = "29 South St. South #202 Uxbridge ON L9P 1V9";
proData['prov_999998']["phone"] = "555-555-5555";
proData['prov_999998']["fax"] = "444-444-4444";
and access it with (i.e.)
providerData['prov_999998']["address"];
Now if prov_999998 is a variable then you should indeed access it without the quotes i added, but make sure that it has a value assigned, and that this value still persists when you try to use it in your function ..
original answer
You should wrap the prov_999998 in quotes 'prov_999998' to make it a literal, otherwise it is treated as a variable.
proData['prov_999998'] = new Array();
proData['prov_999998']["address"] = "29 South St. South #202 Uxbridge ON L9P 1V9";
proData['prov_999998']["phone"] = "555-555-5555";
proData['prov_999998']["fax"] = "444-444-4444";
and
function switchPro(value) {
document.getElementById("letterheadName").value = value;
document.getElementById("letterheadAddress").value = providerData['prov_999998']["address"];
document.getElementById("letterheadAddressSpan").innerHTML = providerData['prov_999998']["address"] ;
document.getElementById("letterheadPhone").value = providerData['prov_999998']["phone"];
document.getElementById("letterheadPhoneSpan").innerHTML = providerData['prov_999998']["phone"];
document.getElementById("letterheadFax").value = providerData['prov_999998']["fax"];
document.getElementById("letterheadFaxSpan").innerHTML = providerData['prov_999998']["fax"];
}
The fact there are enough indexes to get to 999998 in a Javascript memory structure is worrisome. You're definitely going to knock a browser over if much of the preceding entries are loaded alongside it.
Is there anything wrong with calling the index 999 instead of 0999?
It looks like you're trying to use strings to index the secondary items in the array, rather than indexes - like 'address' and 'phone'.
So, your structure should be hashmaps of hashmaps:
var providerData = {
'0999': {
address: '321 Sesame St',
zip: '12345'
},
'1000': {// more here
}
};
alert(providerData['0999']['address']); // alerts "321 Sesame St"
But you should consider the amount of data loaded into it.
Guess your associative array is wrong (or your code lacks info).
proData[prov_999998] = new Array();
should be
proData['prov_999998'] = new Array();
and so on. Anyhow, you could use javascript objects to do that in a neat way.

Categories