Looping Array with a variable as a property - javascript

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

Related

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.

associative array inside array

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.

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.

Convert multidimensional array to array of objects in javascript

I have a multidimensional array (retdata[R][C]) that basically looks like a spreadsheet of cells. R represents the rows, C the columns. I want to create an array of objects so that I get the following
[{retdata[1][1]:retdata[2][1],retdata[1][2]:retdata[2][2],retdata[1][3]:retdata[2][3] },
{retdata[1][1]:retdata[3][1],retdata[1][2]:retdata[3][2],retdata[1][3]:retdata[3][3] },
{retdata[1][1]:retdata[4][1],retdata[1][2]:retdata[4][2],retdata[1][3]:retdata[4][3] },
etc...
]
The resulting array should be:
[{"Col1":"dataR2C1","Col2":"dataR2C2", "Col3":"dataR2C3"},
{"Col1":"dataR3C1","Col2":"dataR3C2", "Col3":"dataR3C3"},
{"Col1":"dataR4C1","Col2":"dataR4C2", "Col3":"dataR4C3"},
etc...
]
I have tried a number of options without success. Any help would be greatly appreciated.
Here is one example I have used but it id not serializing the objects properly.
var TABLE = [];
for (var i=2; i<=rows; i++) {
var ROW = {};
for (var j=1; j<=columns; j++){
name = retdata[1][j].toString;
value = retdata[i][j].toString;
ROW += {name: value}
}
TABLE += ROW;
}
This is like a CSV-parser, the first row of your table are the keys for the line-objects. Your function would work, but you need to correct your array indices: they always start at 0, running up to n-1. Also, you need to learn a bit JavaScript syntax:
something.toString does not call the toString function on that value, but gets that function (it's just an object).
You don't need toString at all - where needed, values are automatically casted
You can't add key-value-pairs to object with a simple operator. You will need to assign the value to that property of an object, with the bracket notation. The += operator would have casted the values to strings and concatenated them.
It's the same with arrays. You could use the .push() method, or just assign to a numerical key - the javascript array object will automatically update its length.
var retdata = […];
var table = [],
keys = retdata.shift(); // get & remove the first row
for (var i=0; i<retdata.length; i++) {
var row = {};
for (var j=0; j<retdata[i].length; j++)
row[ keys[j] ] = retdata[i][j];
table[i] = row;
}
Thank you Bergi. Here is my final solution:
var TABLE = [];
for (var i=2; i<=rows; i++) {
var ROW = {};
for (var j=1; j<=columns; j++){
ROW [retdata[1][j]] = retdata[i][j];
}
TABLE[i]= ROW;
}
which works. The shift did not work as expected but above code is just what I needed. Thanks!

javascript array query

am trying to loop and get the values of names from this array , but am not able..really frustrated with javascript
can anyone please help and guide me to do this and for more complex arrays.. i cant seem to find and tutorial good to show examples of this
thank you , here is the code
var object={name:'angelos',name:'nick',name:'maria'};
var i;
for (i = 0; i < object.length; i += 1) {
document.writeln(object[name][i]);
}
That's an object, not an array. You can make it a simple array instead:
var arr = ['angelos', 'nick', 'maria'];
for (var i = 0; i < arr.length; i++) {
document.writeln(arr[i]);
}
Or, if you want to have objects inside the array (not needed if every object has just one key):
var arr = [{name: 'angelos'}, {name: 'nick'}, {name: 'maria'}];
for (var i = 0; i < arr.length; i++) {
document.writeln(arr[i].name);
}
First of all, your object has duplicate keys name. This is poor code and will throw an error in strict mode.
I would also use either a for ... in loop or Array.forEach here, because much less code is required to implement the desired effect.
Seems like you need to use an Array:
var arr = ["nick", "maria", "chaz"];
arr.forEach(function (name) {
document.writeln(name);
});
You can use Array.forEach, which passes in each index to an anonymous function.
Alternatively, if you wanted each person to be an Object:
var people = [{name: 'chaz', title: 'mr'}, {name: 'nick', title: 'mr'}, {name: 'maria',title: 'ms'}];
for (i in people) {
if (!people.hasOwnProperty(i)) { continue; }
var person = people[i];
document.writeln(person.name);
}
References
Take a look at Array.forEach here
A good reference on for ... in loops here
You can put your data in an array and fill it with objects containing a name attribute (and others e.g. adress or so, if you like to)
http://jsfiddle.net/5NK6x/
var obj=[{name:'angelos'}, {name:'nick'}, {name:'maria'}],
i;
for (i = 0; i < obj.length; i += 1) {
document.write(' ' + obj[i]['name']);
}​
First of all, that is an object, not an array. You probably meant to have an array of objects. I'm saying that because you have three keys all called name. Keys must be unique. like this:
var people = [{name: 'angelos'}, {name:'nick'}, {name:'maria'}];
In that case you would loop through like this:
for (var i = 0; i < people.length; i++) {
document.writeln(people[i].name);
}
Example: http://jsfiddle.net/lbstr/cMqaH/
This is a mix between an array and JSON. If your data looked like this:
var object = [{"name":"angelos"},{"name":"nick"},{"name":"maria"}];
You'd be able to access the elements like so:
for(var i=0,i<object.length,i++)
{
alert(object[i].name);
}

Categories

Resources