associative array inside array - javascript

I have an array within an array as follows:
var array = new Array();
for ( i = 0; i < start.length; i++) {
array[i] = {};
array[i]['properties'] = {};
for(property in start[i].properties ){
//start[i].properties[property] --> ['Type'] = 'any string'
array[j]['properties'][property] = start[i].properties[property];
}
array[i]['id'] = start[i].getId();
}
So in the end I've an array with different elements like 'id' and an element as an array in this array (properties).
But when I use this array in another function, I can't reference to this inner array:
for (var v = 0; v < array.length; v++) {
console.log(array[v][properties]['Type'])
}
The "array[v][properties]['Type']" is not defined..... Why?

You're trying to access the variable properties, not the key properties The proper way to do that would be with array[v].properties.Type.
It's also better not to use bracket syntax unless you must - using dot syntax makes for more easily readable code.
The correct term for JavaScript btw is object, not associative array.

Related

Sorting custom objects - couple of items always end up out of place

I am trying to sort a 2D array of custom objects, inside each inner array, based on one of the properties. This sub-arrays each represent one class, the outer array all the classes in the school. My strategy is as such:
Make a copy of the arry to provide a framework with the correct number of subarrays and indeces
Pass a copy of the sub-array to variable
Iterate over that array (the class) and pull out the last name from the object (which holds a number of other pieces of data on the child) and place it in an array that will be the index
Sort the index
Iterate over the class array, find the position of the last name in the index array, and insert the object into that index into the copied 'school'.
But this is not working. In some instances, one or two objects end up in the wrong place, in other instances it completely out of order. I have tried inspecting my index and comparing it with the 2D array, but the index is correct and I can't figure out why its not working. Here is the code:
var studentsInClass = // I have a function here that returns the 2D array of classes containing custom objects
var sortedStudentsInClass = studentsInClass;
var singleClassHolder = [];
var studentIndex = [];
// each iteration is for a single class
for(var i = 0; i < studentsInClass.length; i ++){
studentIndex = [];
singleClassHolder = studentsInClass[i];
// populate the student reference index
for(var j = 0; j < singleClassHolder.length; j++){
studentIndex.push(singleClassHolder[j].ID);
}
studentIndex.sort();
// iterate through students of single class, placing them in alphabetical order
for(var k = 0; k < singleClassHolder.length; k++){
sortedStudentsInClass[i][studentIndex.indexOf(singleClassHolder[k].ID)] = singleClassHolder[k];
}
}
return sortedStudentsInClass;
}
In case the object is important:
function Child(last, first, id, classroom, serviceDays, eligibility){
this.lastName = last;
this.firstName = first;
this.ID = id;
this.class = classroom;
this.maxServiceDays = serviceDays;
this.eligibility = eligibility;
}
And just a side note, it may seem extraneous having created the new singleClassHolder variable. After I noticed I did that, I removed it and just iterated through the 2D array, but that resulted in even more elements out of place.
Make a copy of the arry
var sortedStudentsInClass = studentsInClass;
This won't make a copy. It only makes one variable reference the other in memory. They both refer to the same array in memory. See related answer here.
The easiest way to fix the code is by declaring sortedStudentsInClass as a new array.
var studentsInClass = get2DArrayOfClasses();
var sortedStudentsInClass = [];
/*...*/
for(var k = 0; k < singleClassHolder.length; k++){
sortedStudentsInClass[i] = sortedStudentsInClass[i] || [];//declare inner array, if not present
sortedStudentsInClass[i][studentIndex.indexOf(singleClassHolder[k].ID)] = singleClassHolder[k];
}

JavaScript for loop Index becomes arrayIndex

I have the following JavaScript code fragment
var ip = new Array();
// This array filled with values and passed to function
function calculateTime(ip) {
for (i in ip) {
window.alert(i);
if (!i in myArray) {
myArray[i] = 0;
} else {
myArray[i] += 1;
}
}
}
I expect i to be an index (0, 1, 2 ...) but sometimes window.alert prints "arrayIndex" and because of that my code doesn't work correctly. Can someone explain me the reason? I am new in JavaScript.
for in will loop over all the enumerable properties of an object.
None of the properties that come with an array are enumerable in modern browsers, but any that are added (such as the normal array indexes or any custom named properties) will be.
Somewhere you have some code that is adding an arrayIndex property to your array and it is coming up when you loop over it.
var myArray = [];
myArray[0] = 1;
myArray[1] = 1;
myArray[2] = 1;
myArray.arrayIndex = 1;
for (prop in myArray) {
console.log(prop);
}
If you only want to get numerical indexes, then use a standard for loop.
for (var i = 0 ; i < myArray.length ; i++) {
console.log(i);
}
For arrays, you should use a numeric variable rather than in:
for(var i = 0; i < ip.length; i++)
in is to iterate over the keys of an Object, but even there you have to take much care to filter out inherited properties.
Now, since arrays are objects too in JavaScript, you can assign them object properties:
ip["arrayIndex"] = 'some value';
Then "arrayIndex" will show up in a for...in iteration, whereas in a "normal" for loop, it won't.
Use either
for(var i=0; i<ip.length; i++){
//your code
}
or
ip.forEach(function(val,i){
// your code
});
The for(var x in y) loop works best for Object rather than Array. When you use it on arrays it will loop through all properties including named ones like length not just numerical indices.

Looping Array with a variable as a property

Here is an list (array) of objects, objects contains some properties, I want to read the properties and bind it to cell of the table! the problem is I can't set the variable as a property of objects in array like
result[index].properties[iindex]
function btnSuccesCallBack(result) {
var customergrid = document.getElementById("customergrid");
GridBind(customergrid, result,["CustomerID", "CustomerName", "PhoneNumber", "ProjectName"] );
}
function GridBind(customergrid, result, properties) {
for (var index = 0; index < result.length; index++) {
var headertr = document.createElement("tr");
for (var iindex = 0; iindex < properties.length; iindex++) {
var headertd = document.createElement("td");
headertd.innerHTML = '&nbsp' + result[index].properties[iindex] + '&nbsp';
headertr.appendChild(headertd);
}
customergrid.appendChild(headertr);
}
}
GridBind() is library tool so Properties of different tables is not the same. so I need to find some way to looping any object property.
You can also access a property by using [] notation instead of . notation. For example:
result[index][properties[iindex]]
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
You should access the object like:
result[index][properties[iindex]]
and not with the . (dot) notation

How to convert Javascript array to JSON string

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}
Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

how to generate arrays automatically in javascript?

I want to make a loop that makes arrays automatically and assign the values to it.
The problem is how to generate the array itself automatically.
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray1 = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray1.push($("#"+idOfInput).val());
}
}
I want the loop to generate the array itself automatically like
catesArray1
catesArray2
catesArray3
and so on..
You need an object or an array to hold the multiple arrays you wish to create. Maybe something you are looking for is like the following?
var arrayHolder = new Array();
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var attGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
arrayHolder.push(catesArray);
}
If you want the arrays to be in global namespace, You can try
window['catesArray' + attGetter] = [];
...
window['catesArray' + attGetter].push(...)
Else you can create a hash object and use it to hold the reference
var obj = {};
.....
obj['catesArray' + attGetter] = [];
.....
obj['catesArray' + attGetter].push(...)
In that case you will have to create one new array that holds all the cacatesArrays from first for loop
var catesArrayContainer = new Array(); //<<<---------------------
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
catesArrayContainer.push(catesArray); //<<<--------------------
}
EDIT :
This happens because the scope of variable catesArray1 was limited. When the loop enters next iteration the catesArray1 gets reinitialized, thus losing all the previously stored values...
Now in the code I have posted, we are storing every instance of catesArray1 in another array, and your values persist out side of the for loop
You can do something like this for 4 arrays of 5 elements each
yourarray=[];
for (i = 0; i <4; i++) {
temparray=[];
for (j = 0; j < 5; j++) {
temparray.push($('#'+whateverID+'_'+i+'_'+j)) //your values here
}
yourarray.push(temparray);
}
Check it on this JSFiddle. open chrome console to see array
If you want to create array within loop from index
You can use eval to evaluate javascript from strings but i wont use that unless there is no other way. you can see both above and eval method in this Fiddle. Open Chrome console to see array values
Just a comparison of using eval and 2D array
Open console in chrome while you run this jsFiddle and you will see the difference in eval and 2darray in context of this question.
You should assign them to an object. In this case, make an object variable before the first for-loop to hold all arrays:
var allArrays = {};
for(var attGetter=1; attGetter <= num; attGetter++){
var currentArray = allArrays['catesArray' + attGetter] = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
currentArray.push($("#"+idOfInput).val());
}
}
Instead of attempting to create & allocate dynamically named variables, I would think of this more of an array of array's if you will. In other words, create an array that holds all of the arrays you want:
var collections = []; // Literal notation for creating an array in JS
From here, it's a matter of making each value you create within this array its own array:
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = [];
// Have another loop that fills in the values array as expected
collections.push(values); // Each element at collections[i] is its own array.
}
If you truly need named elements, you could potentially do something very similar with just an object {} instead, and refer to each element by a name you create.
var collections = {}; // Literal notation for an object in JS
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = []; // Literal notation for an array in JS
// Fill in the values array as desired
var name = 'arr' + i; // How you'll refer to it in the object
collections[name] = values;
}
I suggest the former though, since it does not sound like you need to have explicit names on your arrays, but just want multiple layers of arrays.

Categories

Resources