how to create and assign a value to a variable created dynamically? - javascript

I'm trying to get this to work:
function whatever(arg) {
eval(arg) + '_group' = [];
}
The purpose is to have only 1 function instead having three with basically the same content but with different variable names.
At the end I want to have something like:
a_group = [];
b_group = [];
Doing this way, I'm getting the error:
ReferenceError: Invalid left-hand side in assignment
EDIT
Here is the original function that I'm trying to make work. But it won't work.
function collect_all_values_for(field_name) {
switch(field_name) {
case 'states':
use = 'state';
case 'cities':
use = 'city';
case 'neighborhoods':
use = 'neighborhood';
}
window[field_name + '_group'] = [];
n_fields = $('[id^=' + use + '_]').length-1;
i = 0;
field_value = 0;
for (i = 0; i<= n_fields; i++) {
if (i == 0) {
field_value = $('#' + use).val();
}else{
field_value = $('#' + use + '_id' + i).val();
}
//states_group.push(field_value);
window[field_name + '_group'].push(field_value);
}
}
Looking on the console output:
states_group
[undefined, undefined, undefined]
And then I should be able to call it as:
collect_all_values_for('states');
collect_all_values_for('cities');
collect_all_values_for('neighborhoods');
Thanks in advance.

function whatever(arg) {
window[arg + '_group'] = [];
}
This will set a_group, b_group as global variable.
To access those variable use:
window['a_group'], window['b_group'] and so on.
According to edit
In your switch you should use break;.
switch(field_name) {
case 'states':
use = 'state';
break;
case 'cities':
use = 'city';
break;
case 'neighborhoods':
use = 'neighborhood';
break;
}
Using local Object (without window object) and better
var myObject = {};
function whatever(arg) {
myObject[arg + '_group'] = [];
// output: { 'a_group' : [], 'b_group' : [], .. }
}
// to set value
myObject[arg + '_group'].push( some_value );
// to get value
myObject[arg + '_group'];

Although you really shouldn't use eval this should help
eval(arg + '_group') = [];

Just to increase #theparadox's answer.
I prefer to use the following way to make a switch.
var options = {
'states' : 'state',
'cities': 'city',
'neighborhoods': 'neighborhood'
};
use = options[field_name];
demo
Or if you just want to remove the last letter, you can do this.
use = field_name.slice(0,-1);
demo

Related

Have a lot of variables that are in order. I need to convert them using JavaScript to contain something else but don't want to do it one by one

First of all I'm not a programmer. I need to use some really basic HTML, CSS and XML for my work. The program I am using allows running javascripts, too.
I usually have a lot of variables from my XML files. They go by something like this:
VAL001
VAL002
VAL003
VAL004
You get it.
These variables are often checkboxes. The values can be either 'Checked' or 'Unchecked'.
Instead of embedding these variables in the HTML code, I tend to convert it to something else so it gets nicer. Like this:
if ( VAL001 == 'Checked' ) CHK001 = '✓';
else CHK001 = '';
When this is done, I insert CHK001 (instead of VAL001) in the HTML so I get a nice check mark if the box was checked and nothing when it was not checked. When there are a lot of these boxes it's not too effective to do it one by one.
What I tried in JavaScript is:
var i;
for ( i = 1, i <= 9, i++ ) {
if ( VAL00$i == 'Checked' ) CHK00$i = '✓'
else CHK00$i = '';
}
var j;
for ( j = 10, j <= 99, j++ ) {
if ( VAL0$j == 'Checked' ) CHK0$j = '✓'
else CHK0$j = '';
}
I thought that this would replace the last digits with i and j and I would get what I need. Unfortunately this just brings up a ReferenceError saying that VAL00$i can't be found.
If I replace the $i and $j with [i] and [j] I get the same ReferenceError but this time i and j are not told to be wrong so I get that VAL00 can't be found. A simple solution would really speed up things for me. Thank you in advance!
You could put your variables in an array and use map to check and change the variables to be a tick or not.
var array = [
VAL001,
VAL002,
VAL003,
VAL004
];
var newArray = array.map(val=>{
if (val === 'Checked') return '✓';
else return '';
});
Alteratively, if you need to know the names of the variables after checking everything you could use an object.
var obj = {
VAL001: VAL001,
VAL002: VAL002,
VAL003: VAL003,
VAL004: VAL004
};
var newObj;
for (var i of Object.keys(obj){
if (obj[i] === 'Checked') newObj[i] = '✓';
else newObj[i] = '';
}
If you are having VAL001 variables as property in obj then you can perform like below.
Here i.toString().padStart(3, 0), for i = 1 it will return 001 similarly for i=10 it will return 010; You can access property of object with obj[propertyName]. So these values will be accessible with obj[VAL${index}].
var obj = {
VAL001: 'Checked',
VAL002: '',
VAL003: 'Checked',
VAL004: '',
VAL010: '',
VAL099: 'Checked',
};
var result = {};
for (var i = 1; i <= 99; i++) {
let index = i.toString().padStart(3, 0);
if (obj.hasOwnProperty(`VAL${index}`)) {
if (obj[`VAL${index}`] == 'Checked') result[`CHK${index}`] = '✓'
else result[`CHK${index}`] = '';
}
}
console.log(result);
If you are having variables in global scope then you can use windows["VAL001"].
var VAL001 = 'Checked',
VAL002 = '',
VAL003 = 'Checked',
VAL004 = '',
VAL010 = '',
VAL099 = 'Checked';
for (var i = 1; i <= 99; i++) {
let index = i.toString().padStart(3, 0);
if (window.hasOwnProperty(`VAL${index}`)) {
if (window[`VAL${index}`] == 'Checked') window[`CHK${index}`] = '✓'
else window[`CHK${index}`] = '';
console.log(`CHK${index} = ` + window[`CHK${index}`]);
}
}
We are lacking some information about your environment, but assuming your framework gives you a set of global variables, this should get you started:
for (var i=1, i<=99, i++) {
var i_padded = i.toString().padStart(3, 0);
if (window["VAL" + i_padded] == 'Checked') {
window["CHK" + i_padded] = '✓';
} else {
window["CHK" + i_padded] = "";
}
}
In order to access your global variables I am using the window object here. This is assuming you are running this JS in a browser or browser-like environment.

Build object in JavaScript from PHP form input name

There are a couple of similar questions but none covers the case when a string looks like some-name[][some-key]. I have tried JSON.parse('some-name[][some-key]'); but it doesn't parse it.
Is there a way to convert such string to a JavaScript object that will look like { 'some-name': { 0: { 'some-key': '' } } }?
This is a name of a form field. It's normally parsed by PHP but I'd like to parse it with JavaScript the same way. I basically have <input name="some-name[][some-key]"> and I'd like to convert that to var something = { 'some-name': { 0: { 'some-key': VALUE-OF-THIS-FIELD } } }.
Try this:
JSON.parse('{ "some-name": [ { "some-key": "" } ] }');
I don't know exactly how you're doing this, but assuming they are all that format (name[][key]) and you need to do them one by one - this works for me:
var fieldObj = {};
function parseFieldName(nameStr)
{
var parts = nameStr.match(/[^[\]]+/g);
var name = parts[0];
var key = typeof parts[parts.length-1] != 'undefined' ? parts[parts.length-1] : false;
if(key===false) return false;
else
{
if(!fieldObj.hasOwnProperty(name)) fieldObj[name] = [];
var o = {};
o[key] = 'val';
fieldObj[name].push(o);
}
}
parseFieldName('some-name[][some-key]');
parseFieldName('some-name[][some-key2]');
parseFieldName('some-name2[][some-key]');
console.log(fieldObj); //Firebug shows: Object { some-name=[2], some-name2=[1]} -- stringified: {"some-name":[{"some-key":"val"},{"some-key2":"val"}],"some-name2":[{"some-key":"val"}]}
o[key] = 'val'; could of course be changed to o[key] = $("[name="+nameStr+"]").val() or however you want to deal with it.
Try this:
var input = …,
something = {};
var names = input.name.match(/^[^[\]]*|[^[\]]*(?=\])/g);
for (var o=something, i=0; i<names.length-1; i++) {
if (names[i])
o = o[names[i]] || (o[names[i]] = names[i+1] ? {} : []);
else
o.push(o = names[i+1] ? {} : []);
}
if (names[i])
o[names[i]] = input.value;
else
o.push(input.value);
Edit: according to your updated example, you can make something like this (view below). This will work - but only with the current example.
var convertor = function(element) {
var elementName = element.getAttribute('name');
var inpIndex = elementName.substring(0, elementName.indexOf('[')),
keyIndex = elementName.substring(elementName.lastIndexOf('[') + 1, elementName.lastIndexOf(']'));
var strToObj = "var x = {'" + inpIndex + "': [{'" + keyIndex + "': '" + element.value + "'}]}";
eval(strToObj);
return x;
};
var myObject = convertor(document.getElementById('yourInputID'));
Example here: http://paulrad.com/stackoverflow/string-to-array-object.html
(result is visible in the console.log)
old response
Use eval.. but your string must have a valid javascript syntax
So:
var str = "arr[][123] = 'toto'";
eval(str);
console.log(arr);
Will return a syntax error
Valid syntax will be:
var str = "var arr = []; arr[123] = 'toto'";
var x = eval(str);
console.log(arr);

javascript array - accessing json type of objects

The code:
function getDummyDetails(){
var userDetailsMap = [];
userDetailsMap.push({key:'APPCODE', value:'41'});
userDetailsMap.push({key:'WORKERNUMBER', value:'1234567'});
userDetailsMap.push({key:'ACCOUNTID', value:'DEVELOP'});
userDetailsMap.push({key:'NAMEFIRST', value:'John'});
userDetailsMap.push({key:'NAMELAST', value:'Developer'});
return userDetailsMap;
}
function someOtherFunction () {
var userDetails = getDummyDetails();
document.getElementById("userName").innerHTML = "User Name: " + userDetails[3].value + ", " + userDetails[4].value;
}
Here, it works fine but I can not use the array index here like userDetails[3].value. I was trying to do something like this
userDetails["APPCODE"].value; // just a pseudo code
How can I index this array with that string values but not an integer?
You should create an object instead of an array. That way you'll be able to access it via its key:
function getDummyDetails() {
return {
'APPCODE':'41',
'WORKERNUMBER':'1234567',
'ACCOUNTID':'DEVELOP',
'NAMEFIRST':'John',
'NAMELAST':'Developer'
};
}
function someOtherFunction () {
var userDetails = getDummyDetails();
userDetails["APPCODE"] // 41 - use it however you want...
}
You need to create an object, not an array:
var userDetailsMap = {
APPCODE:41
}
var value = userDetailsMap["APPCODE"];//value now = 41
If you don't want to change your structure, you can iterate over your array:
for (var i = 0, len = userDetailsMap.length; i < len; i++) {
if (userDetailsMap[i].key == 'APPCODE') {
var val = userDetailsMap[i].value;
// do something with the value here
}
}

Delete row from Object

I have an object containing an array:
<script type="text/javascript">
var statusData = {
Status: []
};
var uniqueCounter = 1
function createJsonFmtData() {
// Used as unique id at client side
var uniqueCounter =uniqueCounter + 1;
statusData.Status.push({
"Name": Name,
"Time": Time,
"Email": Mail,
"Name": Type,
"Value": Value,
"uniqueId": uniqueCounter
});
}
function DelNewlyCreStatusRow(rowId) {
// First pop elment from json data
var val;
for (val = 0; val < statusData.Status.length; ++val) {
if (statusData.Status[val].uniqueId == rowId) {
delete statusData.Status[val];
break;
}
}
</script>
When try to call DelNewlyCreStatusRow it gives the error:
TypeError: statusData.Status[val] is undefined
I am not able to figure it out here where as I have declared it as global.
This is because you are trying to delete from the array incorrectly. delete operator is quite funny on arrays. It replaces element with undefined. Check this out:
>>> var A = [1, 2, 3];
>>> delete a[1];
>>> A;
[1, undefined, 3];
Thus calling DelNewlyCreStatusRow multiple times will throw an exception, because statusData.Status[val].uniqueId cannot be evaluated ( statusData.Status[val] is undefined ).
To fix this use this code instead of delete:
var val;
for (val = 0; val < statusData.Status.length; ++val) {
if (statusData.Status[val].uniqueId == rowId) {
statusData.Status.splice( val, 1 );
break;
}
}
Note that splice modifies an array, so if you want to do multiple deletes in one go, then you will have to replace for loop with while ( and refactor the code a bit ). This is not needed here because of break statement.
You should replace
delete statusData.Status[val];
with
statusData.Status.splice(val,1);
val -= 1;
to remove an object in an array.
The function DelNewlyCreStatusRow missing a closing '}'
function DelNewlyCreStatusRow(rowId) {
// First pop elment from json data
var val;
for (val = 0; val < statusData.Status.length; ++val) {
if (statusData.Status[val].uniqueId == rowId) {
delete statusData.Status[val];
break;
}
}
}
You made an Error in your Code at the second var declaration inside the Function.
var uniqueCounter = uniqueCounter + 1 => NAN + 1.
You dont need the var a Second time so it's just
uniqueCounter = uniqueCounter + 1 => 2.
Then delete works fine in my Case.
<script type="text/javascript">
var statusData = {
Status : []
};
var uniqueCounter = 1
function createJsonFmtData() {
var statusName = $('#<%= ddlStatus.ClientID %> option:selected').text();
var dateTime = $("#body_ctl04_ctl02").val();
var forceMail = ($("#chkForceMail").is(':checked')) ? 1 : 0;
var noteType = $('#divTrackId').text();
var dataValue = $("#<%=txtTrackId.ClientID %>").val();
var curLogedUserName = $("#<%=curLoginUserName.ClientID %>").val();
// Used as unique id at client side
uniqueCounter = uniqueCounter + 1;
statusData.Status.push({
"statusName" : statusName,
"dateTime" : dateTime,
"forceEmail" : forceMail,
"typeName" : noteType,
"dataValue" : dataValue,
"uniqueId" : uniqueCounter
});
}
function DelNewlyCreStatusRow(rowId) {
// First pop elment from json data
var val;
for ( val = 0; val < statusData.Status.length; ++val) {
if (statusData.Status[val].uniqueId == rowId) {
console.log(typeof(statusData.Status[val]));
delete statusData.Status[val];
break;
}
}
}
createJsonFmtData();
console.log(statusData);
DelNewlyCreStatusRow(2);
console.log(statusData);
</script>

How to use $.extend() with variables

I'm trying to make a script to use multiple values in window.location.hash but i'm having a problem with the $.extend() function of jquery
I've tried two ways, but both didn't work out.
var MultiHash = {
params: {},
getHash: function () {
var hashString = document.location.hash.replace('#', '').split('&');
for (var i=0; i < hashString.length; i++) {
var key = hashString[i].split('=')[0];
var value = decodeURIComponent(hashString[i].split('=')[1]);
// First way
var a = {key: value};
// Second way
var a = {};
a[key] = value;
$.extend(params, a);
}
return params;
},
...
}
Is anyone seeing the problem?
first you should write :
$.extend(this.params, a); or you cant access param
there may be other issues.
EDIT
it makes sense you return a instead of this.params in my opinion.
$.extend(a,this.params);
return a
There are two problems wrong with what you're trying to do. The first of which being a reference problem as the params variable for that object should be referenced as this.params. The second problem being that you are not saving the result of the object extension. All of this occurs in the following line:
$.extend(params, a);
It should read something like this instead:
this.params = $.extend(this.params, a);
try this one :
var MultiHash = {
params: {},
getHash: function () {
var hashString = document.location.hash.replace('#', '').split('&');
var a = [];
for (var i=0; i < hashString.length; i++) {
var key = hashString[i].split('=')[0];
var value = decodeURIComponent(hashString[i].split('=')[1]);
a.push(key + ":'" + value + "'");
}
$.extend(this.params,(new Function("return {" + a.Join(",") + "}"))());
return this.params;
},
...
}

Categories

Resources