Convert string to become variable - javascript

I have multiple variables containing JSON as string (received from AJAX).
data.output_data_1234
data.output_data_5678
I convert them to Array:
var outputdataarr = new Array(data.output_data_1234);
This works fine, but how do I add a number to the var name:
var outputdataarr = new Array('data.output_data_'+formid+'');
this one does not work.
formid contains a proper number.
This does not work too:
var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);
Please help. Thanks.

You probably mean, you need something like this:
var outputdataarr = new Array(data['output_data_'+formid]);
You can only use string in square brackets as an object field identifier. It cannot contain '.'.
UPDATE:
However, you will probably need a loop to fill the whole array, e.g.
var outputdataarr = new Array();
for (var i=1000; i<2000; i++) {
outputdataarr.push(data['output_data_'+formid]);
}

Use [] instead of new Array is better.
var outputdataarr = [];
outputdataarr.push(data['output_data_'+formid]);
//and so on

Related

Get all match values from two comma separated string

I have two comma separated string as follows,
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
I need to create another string based on the above two,
if hiddenString have unmatching value with strB,then without those unmatched values need to create e new string and also avoid duplicates.
simply says, I need to get all the matching values from both strings.
As the example based on my two string, I'm expecting the following:
varFinalHiddenString = 14172,10062,100;
How can I do this using JavaScript and that should work in safari and IE 11 or its earlier versions. Please help me, I'm new to the JS.
You can first split() strings to generate arrays from them. Then filter() the smaller array by checking the index of the current item with indexOf() in other array:
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var temp1 = hiddenString.split(',');
var temp2 = strB.split(',');
var varFinalHiddenString = temp2.filter(function(s){
return temp1.indexOf(s) > -1;
}).join(',');
console.log(varFinalHiddenString);
Make arrays of the strings, then use the "filter" method. Then convert back to string.
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var hiddenStringAsArray = hiddenString.split(',');
var strBArray = strB.split(',');
var resultObject = $(strBArray).filter(hiddenStringAsArray);
var resultArray = resultObject.toArray();
var resultString = resultArray.join(',');
console.log(resultString);

Creating array of arrays with JavaScript

I have the following code, which when run gives error: TypeError: Cannot read property 'split' of undefined
Here you can run it.
var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = arrayed.split(',');
console.log(newarrayed);
I have myData array, I want to convert it to an array of arrays, splitting first at \n to seperate arrays, and second at , to create the items inside the arrays. so this list would be like:
[[data1, data2, data3], [data4, data5, data6], [data7, data8, data9]]
console.log(arrayed); does something similar, but when I try to access it using arrayed[0][0], it gives me just the first letter.
You're not splitting the strings correctly. You try to split them twice, but the second time fails because you are calling split on an array, not a string. Try looping over them instead.
var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = [];
for (var i in arrayed) {
newarrayed.push(arrayed[i].split(','));
}
console.log(newarrayed);

Is this a valid array (value)?

var leaguetable = new Array();
leaguetable[0]= #leaguetable;
leaguetable[1]= #leaguetable1;
leaguetable[2]= #leaguetable2;
leaguetable[3]= #leaguetable3;
leaguetable[4]= #leaguetable4;
leaguetable[5]= #leaguetable5;
leaguetable[6]= #leaguetable6;
leaguetable[7]= #leaguetable7;
leaguetable[8]= #leaguetable8;
Can you have ID as the array values like I have done? Because this is not working for me at the moment.
You need to wrap your values inside quotes '#leaguetable1', '#leaguetable2'.....
However, you can just use a simple for loop to achieve it automatically instead of manually adding it:
var leaguetable = new Array();
leaguetable[0]= '#leaguetable';
for(var i=1; i<=8; i++) {
leaguetable[i] = '#leaguetable' + i;
}
console.log(leaguetable);
Fiddle Demo
Bo, #foo is not a valid JavaScript expression. You meant '#foo' instead.
Also, you can (should) use an array literal instead of new Array:
var leaguetable = [
'#leaguetable',
'#leaguetable7',
...
'#leaguetable8'
];

Javascript JSON stringify No Numeric Index to include in Data

i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)

Array read problem for map of vectors of strings in javascript

I am a newbie in JS. Here is my code and I believe it should work... but it doesn't.
var pop = new Array();
pop['la'] = new Array('nt','gb','te');
pop['sa'] = new Array('nt','gb');
pop['ha'] = new Array('pc','pa');
var _ecpop="la";
for (var i = 0; i < pop[_ecpop].length; i++)
{
document.write(pop[_ecpop][i]);
}
I just do not know any alternate way to have a map of vectors of a string.
Thanks,
Amir.
That's not an Array, but a Javascript Object, containing Arrays in it's properties. You can use Object and Array literals for that. The advantage is that your code looks much cleaner. There are seldom reasons to use new Array or new Object in javascript code (see for example this SO Question).
var pop = {
la: ['nt','gb','te'],
sa: ['nt','gb'],
ha: ['pc','pa']
}
now you can use
for (var i = 0; i < pop.la.length; i++) {
console.log(pop.la[i]);
}
if a property label is stored in a variable (like you _ecpop), you can use bracket notiation to retrieve it's value:
var laArr = pop[_ecpop];
for (var i = 0; i < laArr.length; i++) {
console.log(laArr[i]);
}
The other way around you can assign a label to an Object:
var _ecpop = 'la';
pop[_ecpop] = ['nt','gb','te'];
document.write is not the preferred way to put things on your page. It's better and just as easy to use some element with an id, and write output to it using innerHTML, for example
document.getElementById('myOutput').innerHTML = '[some output here]';
In javascript, an array can only have numeric indexes, if you want to use textual indexes, you should use object instead.
var pop = new Object();
or
var pop = {};
and then:
pop['la'] = new Array('nt','gb','te');
However, as an object is not an array, it has no length member, but just as an array you can use the for..in to go through all of its values.
Using document.write is not a good choice as it only works during the document loading, not after it. Try to use text nodes or innerhtml instead.

Categories