jQuery loop with an array error - javascript

i have this snippet. As a result i see an error: Invalid left-hand side in assignment.
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
this = jQuery("#sc-dialog ."+value).val();
});
Does anyone can point me to how to fix this?
Thanks.
This is an UPDATE
I need that variable 'text' will have the numbers in the loop: text1, text2, text3... i have made it like this:
var arr = [ "1", "2", "3", "4" ];
jQuery.each(arr, function(index, value) {
var text + index = jQuery("#sc-dialog .text"+value).val();
});
But i got an error: Unexpected identifier. The problem is here: var text + index

Try like this:
jQuery.each(arr, function(index, value) {
arr[index] = jQuery("#sc-dialog ."+value).val();
});

Putting a + after your variable name is a syntax error in your var statement:
var text + index = jQuery("#sc-dialog .text"+value).val()
A valid variable declaration will be either variable name by itself:
var text;
Or the variable name with an assigned value:
var text = jQuery("#sc-dialog .text"+value).val();
The value being assigned can have a + or other operators in it:
var x = y + z - 5 * (a + b);
And in a single var statement you can declared multiple variables with or without values by separating them with commas:
var i, j = 0, k, text = jQuery("#sc-dialog .text"+value).val(), x = 12 + 4;
An array of numbers that follow a simple pattern (in this case array element index plus 1) is kind of pointless when you can achieve the same thing with a standard for loop. EDIT: from your comment it seems like you don't want to process the values within the loop, you want to store the values for later use. You mention wanting text1, text2, etc., but if you need to reference them individually it sounds like your various textareas aren't really a group and it doesn't make sense to process them in a loop at all. But if you insist then you should store the values in an array:
var i,
text = [];
for (i = 1; i <=4; i++) {
text[i] = jQuery("#sc-dialog .text"+i).val();
}
// later in your code
// text[1] is first value,
// text[2] is second value, etc
Note that JS array indexes are zero-based, and array .length is one more than the highest index, but your field numbering starts at 1 - keep that in mind if you later loop over the text array.

You can't use 'this' as a variable name. try something like:
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
var dialogValue = jQuery("#sc-dialog ."+value).val();
});

Related

Parse Javascript output array / Parse URL Hash

I'm trying to parse out a single value from a URL String with three varaibles, and I am currently using the code:
var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);
for (var i = 0; i < hash_array.length; i++) {
hash_key_val[i] = hash_array[i].split('=');
var array = hash_key_val[i];
console.log(array);
}
This code works to parse out the hash, but it creates separate arrays for each item and value like so:
["object1", "value1"]
["object2", "value2"]
["object3", "value3"]
By altering the array to var x = JSON.stringify(array[1]);
I can get the value which is all I need, but I only need the first value, while this code still returns:
"value1"
"value2"
"value3"
How can I alter the code so that the function only outputs value1?
Thanks!
Change the 1 for 0; Arrays start at zero index. Also I am not sure if you are aware that you are looping over the values as you are printing them out.
var arr = [
["object1", "value1"],
["object2", "value2"],
["object3", "value3"]
];
console.log(arr[0][1]);
As Arrow mentioned you need to change the index at which you access array from 1 to 0.
Additionally, why not use map:
var keys = hash_array.map(function(param){
return JSON.stringify(param.split('=')[0]);
}
with keys being ["object1", "object2", "object3"]

Getting the name of an array under another array

Suppose I have this code:
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
Yen_Sid: ["Pirate", "Heroes", "Power"],
};
Calling Rock, Bottom, Stunner and etc. is easy.
document.write(simple.Cicatrix[0]);
However, what if i wanted to get the word Cicatrix and Yen_Sid? I want them to be called because I am going to use them as menus.
Also is it possible to have spaces in array names? Like Yen_Sid turns to Yen Sid. Or should I do a .replace?
Yes, you can have spaces in property names, you just need a delimiter around it:
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
"Yen Sid": ["Pirate", "Heroes", "Power"],
};
However, if you want to loop out the items in a specific order, then you don't want them as object properties, you want them as items in an array. The properties in an object doesn't have a specific order, so when you loop out properties the order depends on the implementation in the browser, and different browsers will give you the properties in different order.
var simple = [
{ name: "Cicatrix", items: ["Rock", "Bottom", "Stunner"] },
{ name: "Yen Sid", items: ["Pirate", "Heroes", "Power"] }
];
To loop through the items and subitems you just need a nested loop:
for (var i = 0; i < simple.length; i++) {
// menu item is in simple[i].name
// subitems are in simple[i].items:
for (var j = 0; j < simple[i].items.length; j++) {
// subitem is in simple[i].items[j]
}
}
Simply use a for loop to go over simple with a replace.
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
Yen_Sid: ["Pirate", "Heroes", "Power"],
};
for(x in simple)
console.log(x.replace('_',' '));
This allows you to iterate over an object's properties
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
It is not possible to have whitespace as you suggest in object notation property names unless you use double quotes like
obj = {"prop 1": [1,2,3]}
var t = obj["prop 1"]
For your first question, getting keys as strings is possible using Object.keys() method. I am not going to write examples here since the documentation I provided earlier has plenty of snippets that shows you how to use it. Other solution would be to use for loop to loop over the keys as Matthew Christianson pointed out in other answer.
And yes, you can have keys that are named with space, but when you're calling them be sure to do it using object.[property] notation, as in:
var x = {
"a b c" : 1234
}
console.log(x["a b c"]); // will log "1234" to Console!
I wouldn't suggest you using names with spaces since your code gets a bit messy using bracket notation, in my opinion. But you can make another object whose keys are keys from your primary object, and values are correctly spelled names, as in:
var names = {
YenSid : "Yen Sid",
SomeName : "Some name",
SomeOtherName : "Some other name"
}
var properObject = {
YenSid = 123,
SomeName = 456,
SomeOtherName = 789
}
And to get a correct name just use names.YenSid
Try this, its an example of how to print out the array to a string.
var text = "";
$.each(simple, function(k) {
text = text + "// " + k + " contains: ";
for ( var i = 0, l = $(this).length; i < l; i++ ) {
text = text + $(this)[i] + ", ";
}
});
console.log(text);

key-value pair undefined in javascript

For some reason I have a string like this:
"id: 123, title: something, category: science, ... "
To make a javascript object containing the key-value pairs I wrote the following method:
function stringToMap(stringToCut){
var map = {};
var listOfPairs = stringToCut.split(",");
for(var i = 0; i < listOfPairs.length; i++){
var pair = listOfPairs[i].split(":");
map[pair[0]] = pair[1];
}
return map;
}
it's important to access it with dot, not with [] brackets.
In chrome debug mode I see the expected object, but when I want to access one of it's element, like:
console.log(obj.title);
I get undefined...
What Am I doing wrong?
It's because there's a space in your key name:
console.log(obj[" title"]); // "something"
To fix this, change your first split to split on ", " instead of just ",":
var listOfPairs = stringToCut.split(", ");
JSFiddle demo.
As a further fix, you'll also want to change your second split to split on ": " rather than just ":", otherwise all your values will begin with spaces.
var pair = listOfPairs[i].split(": ");

Javascript/Jquery Convert string to array

i have a string
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
i tried
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?
Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
​for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}​

Another javascript array challenge

Solving another array manipulation, and I'm taking longer than usual to solve this. I need help in combining array values:
var array1 = ["alpha|LJ", "bravo|MH", "charlie|MH", "delta|MF",
"echo|16", "{foxtrot}|GG", "{golf}|HS"];
var array2 = ["charlie-{golf}-{foxtrot}", "echo-{golf}"]; //some templates
such that the final array be:
final_array = ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF",
"echo-HS-16"];
To make it clear how I arrived with the final_array, alpha, bravo and delta only got their "|" replaced with "-" since they are not found on my array2 template. charlie and echo got the template so the respective values of the {} were replaced based on array1. Array1 honestly is not the best key:value relationship that I could come up for now.
Here are some requirementL:
* Anything in array1 with {} braces are not meant to be templated.
* Keywords in array2 will always have a matching value in array1.
I've read about jquery .map() and thinking that it is achievable using this, maybe together with Regexp. Hope you'll utilize these. Also, if it helps, final_array can be of any order.
I really need to up my knowledge on these two topics... :|
Thank you in advance.
Edit: Updated to match your output and comment some of the madness. This doesn't feel like it's the most efficient, given the split() done to values at the start and then again at the end...but it works.
function funkyTransform( values, templates ){
// Make a copy of the array we were given so we can mutate it
// without rudely changing something passed to our function.
var result = values.concat();
// Map {value} entries for later lookup, and throw them out of the result
var valueMap = {};
for (var i=result.length-1;i>=0;--i){
var pair = result[i].split('|');
if (pair[0][0]=="{"){
valueMap[pair[0]] = pair[1];
result.splice(i,1); // Yank this from the result
}
}
console.log(valueMap);
// {
// "{foxtrot}": "GG",
// "{golf}": "HS"
// }
// Use the value map to replace text in our "templates", and
// create a map from the first part of the template to the rest.
// THIS SHOULD REALLY SCAN THE TEMPLATE FOR "{...}" PIECES
// AND LOOK THEM UP IN THE MAP; OOPS O(N^2)
var templateMap = {};
for (var i=templates.length-1;i>=0;--i){
var template = templates[i];
for (var name in valueMap){
if (valueMap.hasOwnProperty(name)){
template = template.replace(name,valueMap[name]);
}
}
var templateName = template.split('-')[0];
templateMap[ templateName ] = template.slice(templateName.length+1);
}
console.log(templateMap);
// {
// "charlie": "HS-GG",
// "echo": "HS"
// }
// Go through the results again, replacing template text from the templateMap
for (var i=result.length-1;i>=0;--i){
var pieces = result[i].split('|');
var template = templateMap[pieces[0]];
if (template) pieces.splice(1,0,template);
result[i] = pieces.join('-');
}
return result;
}
var output = funkyTransform( array1, array2 );
console.log(output);
// ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF", "echo-HS-16"]
This managed to get your desired output, though I made a few assumptions:
Anything in array1 with {} braces are not meant to be templated.
Keywords in array2 will always have a matching value in array1 (this can easily be changed, but not sure what your rule would be).
Code:
// This is the main code
var final_array = $.map(array1, function (item) {
var components = item.split('|');
// Ignore elements between {} braces
if (/^\{.*\}$/.test(components[0])) return;
components[0] = template(components[0]);
return components.join('-');
});
// Helper to lookup array2 for a particular string and template it
// with the values from array1
function template(str) {
var index = indexOfMatching(array2, str, '-');
if (index == -1) return str;
var components = array2[index].split('-');
var result = [str];
for (var i = 1; i < components.length; i++) {
result.push(array1[indexOfMatching(array1, components[i], '|')]
.split('|')[1]);
}
return result.join('-');
}
// Helper to for looking up array1 and array2
function indexOfMatching(array, target, separator) {
for (var i = 0; i < array.length; i++) {
if (array[i].split(separator)[0] === target) return i;
}
return -1;
}

Categories

Resources