Looping through items in an array of objects - javascript

I have an array of objects.
ABC.getAggregation("V")[0].getItems();
this produces the result:
MY ARRAY OF OBJECTS
In the console i can get the result i am looking for by specifying the position of the item like this:
ABC.getAggregation("V")[0].getItems()[0].getPosition()
ABC.getAggregation("V")[0].getItems()[1].getPosition()
ABC.getAggregation("V")[0].getItems()[2].getPosition()
The result of the above code produces string values e.g "3.4554,43,0".
How can i loop through each item and get the position in my code. just like the above code that i typed in the console. there wont always be 3 objects this is why i cant hard code the above 3 lines.

Try using a the Array.prototype.forEach() function. The function will be called for each element in the array, passing in the element as the first parameter.
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
item.getPosition();
//do something else
});
More on ".forEach()"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

You can treat it like any other array:
var myArray = ABC.getAggregation("V")[0].getItems();
for(var i=0; i< myArray.length; i++){
myArray[i].getPosition(); //Do something with the position.
}

You can use for loop to iterate trough all of them.
for(var i=0; i<ABC.getAggregation("V").getItems().length; i++) {
ABC.getAggregation("V")[0].getItems()[i].getPosition();
}

You can use forEach loop to iterate trough all of them.
ABC.getAggregation("V").getItems().forEach (item, index) {
return ABC.getAggregation("V")[0].getItems()[index].getPosition();
}

A very simple way to iterate through each object in the array is just with a for loop on the array, you don't even need to declare your iterating variable.
ex:
var anArray = ['one', 'two', 'three'];
for( i in anArray){
console.log('index #: ' + i );
console.log(anArray[i]);
}
will print out all the elements in anArray:
index #: 0
one
index #: 1
two
index #: 2
three

!! Apparently this is a good example of how not to do it :P
You can assign the items to an array and loop through them like this:
var items = ABC.getAggregation("V")[0].getItems();
var returnString = "";
for (var key in items ) {
if (items .hasOwnProperty(key)) {
var element = items [key];
returnString += element.getPosition() + ',';
}
}
returnString = returnString.substring(0, x.length-1);
console.log(returnString);

Related

How to work with multidimensional array when the number of dimension is variable?

Hello stackoverflow members.
I come with the following problem:
To start we have
var myArray = [[array1],[array2],[array3],[arrayN],...];
where each array is filled with a known number of strings such as
var array1 = ["a","b"], array2 = ["1","2"], array3=["&","é"];....
and so on.
I'm looking for a method to get this result:
expected result ===> a1&;a1é;a2&;a2é;b1&;b1é;b2&;b2é; ....
If the number of dimension were fixed I could use for loops to iterate and build the result, BUT here the problem is that I want to be able to enter N arrays in the main array myArray and by doing so, I change the depth of the nested loops.
If not do you have some ideas to put me on the track of the solution to this?
Thanks!
EDIT by the way this is what i experimented:
for (i=0; i<myArray[0].length; i++){
for (var j =0; j<myArray[1].length; i++){
for(var k = 0; k<myArray[2].length; k++{
console.log(i+j+k);
}
}
}
BTW i can't find a way to describe a function which would nest N for loops where N is myArray.length + 1 (the number of arrays in myArray).
EDIT: i found an iterative way of doing it and wanted to share the solution:JSFiddle
To get a flat list of all cells, something like the following recursive function should work (if you have a non-empty array of arrays, and all array items are strings):
function makeFlatList(inputArray) {
if (inputArray.length == 1) { // if this array has only one array inside
return inputArray[0]; // return the array inside
} else {
var outArr = [];
var arrayShifted = inputArray.slice(1); // remove first subarray from inputarray
var arrayShiftedFlat = makeFlatList(arrayShifted); // recursive call
for (var i=0; i<inputArray[0].length ; i++) { // loop over first array
for (var j=0; j<arrayShiftedFlat.length; j++) {
outArr.push(inputArray[0][i]+arrayShiftedFlat[j]); // add items to outArr
}
}
return outArr;
}
}
Working JSBin here

Retrieving elements from array javascript

I have two arrays in js
var array1=new Array("KS","NB","SD","ND","MN");
var array2=new Array("TX","LA","OK","AR");
Some how I will get the name of the array that should be retrieved.
Now what I want is, if I get
var arrayTobeSelected = 'array1';
If I console.log arrayTobeSelected, what I get is the string 'array1'.
How can I get the elements in the array array1 ?
If arrays are in the global scope, you can do:
console.log(window[arrayToBeSelected]);// you can do [0] or [1] to get specific elements
You're getting a string because:
var arrayTobeSelected = 'array1';
and not:
var arrayTobeSelected = array1;
if you have to get it as string, then just do this:
console.log(eval(arrayTobeSelected));
You can use this code for print all the element of array.
for(var i = 0; i < array.length; i++){
console.log(i + " = " + array[i]);
}
console.log(array);
console.log("end");

Getting object out of an array of objects in JavaScript

sorry I feel this is sort of a stupid question I have searched quite a bit and I cannot find my answer.
I have an array in JavaScript that I am inserting a bunch of elements. The trouble is I cannot then get the values of the elements back out, I think I am getting the property of the actual array. Below is what I am doing and what I am trying to do. Thanks in advance for the help. This is not the full traverse method, it actually does go through a bunch of times. When I previously just had an associative array items[a] it worked perfectly.
var element = { html: "", group: "" };
var array = [];
function traverse(o) {
for (var key in o) {
element.html = "<li class='item'>" + key + " : </li>";
element.group = b;
array.push(element);
}
}
I want to print the html from each element, the issue is I get the .html from only the first element each time.
function printElements() {
for (item in array) {
var element = array.pop();
console.log(element.html);
}
}
I also tried.
function printElements() {
for (item in array) {
console.log(array.html);
}
}
I want to keep the array intact, I do not want to pop and elements I just want to print them.
The main problem isn't to get the data out of the array, it never gets into the array in the first place.
You don't have a bunch of elements in the array, you only have one element that you change and add to the array over and over. When you put it in the array it's not copied, it's just the reference to the element that is placed in the array. You end up with an array full of references to the same single element.
Create a new element for each iteration in the loop when you populate it:
for (var key in o) {
var element = {};
element.html = "<li class='item'>" + key + " : </li>";
element.group = b;
array.push(element);
}
Use a simple for loop instead:
for (var i = 0; i < array.length; i++) {
var item = array[i];
// do stuff
}
It is unadvisable to use the nicer for loop syntaxes on arrays in JavaScript because they will iterate through all key/value pairs in the array, not just the array numeric keys. This is because arrays are objects, too, and the for...in loop syntax does not differentiate between them.
You're not using the iterated object, instead you are using array... change this:
function printElements() {
for (item in array) {
console.log(array.html);
}
}
to this:
function printElements() {
for (item in array) {
console.log(array[item].html);
}
}
jsfiddle
Do it this way:
var array = [];
function traverse(o) {
for (var key in o) {
var b = 'b'; // if that is what you have ment
var element = { html : "<li class='item'>" + key + " : </li>", group : b};
array.push(element);
}
}
function printElements() {
for (var item=0; item<array.length; item++) {
console.log(array[item].html);
}
}
That's because it isn't safe to use for each in case of arrays and you should have new object for each array element.
Be sure not to use delete on array elements either.

concat empty / single item array

Ok, so I have this simple code :
for(var i=0; i<lines.length; i++) {
elements += myFunction(lines[i]);
}
Where elements is an empty array at the start and myFunction() is just a function that returns an array of strings.
The problem is that if myFunction() returns an array with a single string, the += is interpreted as a string concat in place of an array concat.
At the end of the loop the result is just a long string and not an array.
I tried push()ing the values in place of concatenation, but this just gives me a two dimensional matrix with single item arrays.
How can I solve this typecasting problem ? Thank you in advance !
Try :
for(var i=0; i<lines.length; i++) {
elements [i] = myFunction(lines[i]);
}
I suppose it solves the problem.
You can use the Array concat function:
elements = elements.concat(myFunction(lines[i]));
Presumably you want something like:
var arrs = [[0],[1,2],[3,4,5],[6]];
var result = [];
for (var i=0, iLen=arrs.length; i<iLen; i++) {
result = result.concat(arrs[i]);
}
alert(result); // 0,1,2,3,4,5,6
Ah, you want to concatenate the results of a function. Same concept, see other answers.
You can also use myArray[myArray.length] = someValue;
let newArray = [].concat(singleElementOrArray)

Javascript for loop var "i" is treated as a string?

I am using Titanium to build some mobile apps and I noticed that this will give a result that I wasn't expecting.
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i+1);
};
This will print: 01,11,12,13
Is this something particular to Titanium or is it generally in Javascript?
Why isn't 'i' being treated as an integer? I am very confused.
Thanks for your help.
This doesn't directly answer your question, but if you are looping through an array you should not use for (var i in data). This loops through all members of an object, including methods, properties, etc.
What you want to do is this:
for (var i=0, item; i<data.length; i++) {
item = data[i];
}
data is an array, so you use a for loop, not a for-in loop:
var data = [ ... ];
var i;
for ( i = 0; i < data.length; i += 1 ) {
Ti.API.debug( i + 1 );
}
Alternatively, you can use the forEach array method:
data.forEach( function ( val, i ) {
Ti.API.debug( i + 1 );
});
The reason why you see this behavior is that the type of i when using a for-in over an array is string not int. Hence the + is doing string concatenation and not addition. If you want it to be the numerical value then use a for loop
for (var i = 0; i < data.length; i++) {
Ti.API.debug(i + 1);
}
Try this:
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i*1+1);
};
Multiplying i x 1 will force it to recognize it as numeric.
Try this:
Ti.API.debug(parseInt(i)+1);
You can do
data = ['a','b', 'c','d'];
for (var i in data){
console.log(parseInt(i)+1);
};
But it is not recommended. Because in Javascript for..in loop is for key:value pairs (Objects). So if use it with an array each index is converted to string as key.
so always use for(i = 0; i < length; i++) with arrays.
This is because javascript handles for-each loop this way.
In other languages for(i in datas) will loop through each data.
But in javascript the i will have index value instead of data. so you have to get data by datas[i].

Categories

Resources