SCRIPT28: Out of stack space - javascript

Getting stack out of space in IE 10,11 when I try encode a array of data to Json and store it into an array
var SelPeriod = Ext.getCmp('SelectedPeriodGrid');
SelPerioddata = [];
var PeriodsSelected = SelPeriod.getStore('MarkettrackDrillDownPeriods').getRange();
for (var i = 0; i < PeriodsSelected.length; i++) {
SelPerioddata.push(PeriodsSelected[i]);
}
var SelPerioddatajson = [];
SelPerioddatajson = Ext.JSON.encod(SelPerioddata);

Try using only the record's data, like:
SelPerioddata.push(PeriodsSelected[i].data);
You can also rewrite this like:
var selPeriod = Ext.getCmp('SelectedPeriodGrid'),
periodsSelected = selPeriod.getStore('MarkettrackDrillDownPeriods').getRange(),
selPerioddatajson = Ext.JSON.encode(periodsSelected.map(function(record) {
return record.data;
}));

Related

Javascript: Parse string array into object with custom key names and values

So I have a string which contains a list of custom http headers that is in the following format:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
I split that up using the pipe as a delimiter:
var splitHeaders = headers.split("|");
I'm left with an array which I can loop through, and I'm trying to convert that string array into an object. This is what I have so far:
var customHeaders = {};
for (var i in splitHeaders) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
What I'm essentially trying to create is an object called customHeaders to hold values like:
customHeaders = {
"Referer":"https://someurl.com/",
"User-Agent":"Some Browser"
};
Am I doing something wrong?
You are on the right track. Use a more standard form of the for loop using the length of the splitHeaders as a limiter:
for (var i = 0; i < splitHeaders.length; i++) {
Working example:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
var splitHeaders = headers.split('|');
var customHeaders = {};
for (var i = 0; i < splitHeaders.length; i++) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
console.log(customHeaders);
There are also other methods you can use that allow you to convert an array of items into an object, using such as reduce.
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
headers = headers
.split('|')
.reduce(function(obj, val) {
var split = val.split('=');
obj[split[0]] = split[1];
return obj;
}, {});
console.log(headers);

Issue with javascript array variables

I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}

Nested loop to dynamically create objects

I am trying to create a loop or a nested loop that will create one(1) array containing many objects:
// example of the object structure
obj0.country = distAttr[0];
obj0[municipo[0]] = econ[0];
obj0[municipo[1]] = edu[0];
obj0[municipo[2]] = gov[0];
obj0[municipo[3]] = health[0];
obj0[municipo[4]] = infra[0];
obj0[municipo[5]] = social[0];
obj1.country = distAttr[1];
obj1[municipo[0]] = econ[1];
obj1[municipo[1]] = edu[1];
obj1[municipo[2]] = gov[1];
obj1[municipo[3]] = health[1];
obj1[municipo[4]] = infra[1];
obj1[municipo[5]] = social[1];
// ... obj18
This is what i have so far:
// create all the objects, distAttr length is 19
for (var i = 0; i < distAttr.length; i++) {
window['obj'+i ] = {};
};
// distName length is 6
var number = distName.length;
// this loop I can't figure out
for (var j = 0; i < distName.length; j++) {
window['obj'+i ][municipo[j]] = econ[i];
};
// bind the objects to the array
for (var i = 0; i < distAttr.length; i++) {
chartArray[i] = window['obj'+i];
};
You can build the object within a single loop:
// Set up some variables and the field values you will use:
var j,
obj,
ec = municipo[0],
ed = municipo[1],
go = municipo[2],
he = municipo[3],
in = municipo[4],
so = municipo[5];
// Loop through the array.
for (i = 0; i < distAttr.length; i++) {
// Create an object with a country field.
obj = { country: distAttr[i] };
// Populate the other fields.
obj[ec] = econ[i];
obj[ed] = edu[i];
obj[go] = gov[i];
obj[he] = health[i];
obj[in] = infra[i];
obj[so] = social[i];
// Set the array index to contain the object
// (and if you need it then create a global object `objx`
// - not sure if you need it though.)
chartArray[i] = window['obj'+i] = obj;
};

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

Loop through two Array in JavaScript and Constructing a function

I have Two Arrays in Javascript as shown below :
Array one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
Array two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
Now Some how i need to loop through this Array and construct a function as shown
function NoisyData() {
return "" +
"Date,A\n" +
"20061001,3.0\n" +
"20061002,3.1\n" +
"20061003,3.2\n" +
"20061120,4.0\n" ;
}
Please help me as how to do this ??
How about this?
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push('3.0');
two.push('3.1');
two.push('3.2');
two.push('3.3');
function NoisyData() {
var result = "Date,A\n";
for(var i = 0; i < one.length;i++){
result += one[i] + "," + two[i] + "\n";
}
return result;
}
alert(NoisyData());
The faster way for long array is :
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
function NoisyData() {
var ret = [];
ret.push("Date,A");
for (var i=0;i<one.length;i++){
ret.push(one[i]+','+two[i]);
}
return ret.join('\n');
}
alert(NoisyData());
Your code can be a lot shorter. You can't type variables (like Array one) in javascript. To declare an Array most of the time an Array literal is sufficient.
If your arrays have the same length, you can use the code hereby to combine them into the string you need:
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combine = function(a1,a2){
var i = -1, len = a1.length, res = ['Date,A'];
while(++i < len){
res.push(a1[i]+','+a2[i].toPrecision(2));
}
return res.join('\n');
}(one,two);
Try it # http://jsfiddle.net/KooiInc/jdn6U/
You mean
function NoisyData() {
var txt = "Date,A\n"
for (var i=0, n=one.length;i<n;i++) {
txt += one[i]+","+two[i]+"\n"
}
return txt
}
UPDATE based on KooiInc's posts:
<script>
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combined = function(res,two){
var i = one.length;
while(i--){
res[i]+=','+two[i].toPrecision(2);
}
res.splice(0,0,'Date,A');
return res.join('\n')
}(one.slice(0),two);
alert(combined);
</script>
Instead of one.slice(0) one.clone() can be implemented as
Array.prototype.clone = function() { return this.slice(0); }
or just pass one itself instead if it is OK to modify the original array

Categories

Resources