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;
}
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.
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"
I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.
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;