Nested loop to dynamically create objects - javascript

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;
};

Related

Adding dynamic named Javascript object to an array with a for loop

Wondering if it is possible to use a loop to add dynamically named objects to an array, so I don't need to repeat the "push" on an array. Tks !!
let _objA0 = { "name":"regionId", "value":"myRegion" };
let _objA1 = { "name":"vdcId", "value":"myId" };
let _objA2 ... _objA100
let test = []
test.push(_objA0)
test.push(_objA1)
...
test.push(_objA100)
I guess it's the right time to use eval
let test = [];
for(let i = 0; i <= 100; i++) {
test.push(eval(`_objA${i}`));
}
You can access variables (with var keyword) by window object , try this:
var _objA0 = { "name":"regionId", "value":"myRegion" };
var _objA1 = { "name":"vdcId", "value":"myId" };
let test = [];
for(let i = 0; i < 2; i++){
test.push(window['_objA' + i]);
}
console.log(test)

Issue populating an array of objects dynamically in javascript

I am facing an issue when populating an array of the object dynamically in javascript. I have this sample data as below:
I have to populate following arrays with the data from above:
c1_Arr = [];
c2_Arr = [];
var torontoObj = { arName: 'تورونتو', enName: 'Totonto', value: 0 };
var parisObj = { arName: 'باريس', enName: 'Paris', value: 0 };
var londonObj = { arName: 'لندن', enName: 'London', value: 0 };
Now I am looping through the data to set the values from data as:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
if (data.Ind_ID === 101) {
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
I am getting this data in console:
Here I am getting the values of the object i.e. Ind_ID = 102 instead of the object values of Ind_ID = 101 (first object).
How to get the values of the required object using the Ind_ID?
The problem is because even though you have the if condition there but you are updating the value of the objects in the loop and since you have already pushed them objects you still have the reference in the main objects. They get overwritten.
Create the 3 objects (torontoObj, etc.) inside the loop.
Reference is getting updated in the second iteration (where Ind_ID is 102)
You should rather do
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
Your object values are getting updated even after being set inside the if loop, simply because, you're not limiting it from being updated.
You could probably do one of the following 2 things:
The simpler one:
Extract the values of Paris, London and Toronto fields of data only if the Ind
_ID is 101.
like this:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
The more elegant one:
Extract the array element which only matches your condition, in other words filter.
var resultCount = results.features.length;
var data = results.features.filter(feature => feature.attributes.Ind_ID === 101);
parisObj.value = data[0].Paris;
londonObj.value = data[0].London;
torontoObj.value = data[0].Toronto;
console.log(c1_Arr);

SCRIPT28: Out of stack space

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;
}));

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

Categories

Resources