javascript array query - javascript

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

Related

JS - Iterating objects in for loop

I can't seem to figure out this problem. I need to iterate over some objects, as of right now, named column_1, column_2, column_3 and column_4.
How do i use the i variable, to get the correct object?
This is my code right now, which isn't working...
for (var i = 1; i < layouts.columns; i++) {
console.log(layouts.column_[i]);
}
Do you mean you need to iterate over the properties of an object?
It's not like an array. You have to do something like
let keys = Object.keys(layouts.columns);
for(var i = 0; i < keys.length -1; i ++ ) {// do stuff};
or
for (var key in layouts.columns) {
var column = layouts.columns[key];
}
Or like others have mentioned, if all property names are column_x, you could loop through 4, and access like layouts['column_'+i]

js - Declare multidimensional array + push key and value

Where exactly is wrong here? I get a "Cannot read property 'push' of undefined" error, and I believe that's because the array can't be set to multidimensional by simply declaring it in the loop.
var single = [];
for (var i = 0; i < all.length; i++) {
name = all[i].name;
single[name].push(all[i]);
}
What I'm trying to achieve is this structure:
Array (
([name1] => [node1],[node2],[node3]),
([name2] => [node1],[node2],[node3],[node4],[node5],[node6]),
([name2] => [node1],[node2])
etc...
)
I've tried searching here on SO, but so far only got two options:
Option 1: Shorthand in declaring the variable, aka [[]], which doesn't work.
var single = [[]];
Option 2: link Add another loop to work out the array before filling it.
var matrix = []
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
I'd rather find a shorter solution, also because my array elements MUST have the key, while on the solution above they are numbered.
EDIT: since keys in JS array are not an option, would an object do the trick in this case? something like:
var obj = {
key1: value1,
key2: value2
};
obj.key3 = "value3";
You can use object or Map (ES6) data structure to achieve this, e.g.:
var single = {};
for (var i = 0; i < all.length; i++) {
name = all[i].name;
if (!single[name]) {
single[name] = [];
}
single[name].push(all[i]);
}
the result (single object) looks like:
{
name1: [node1, node2, node3],
name2: [node1, node2, node3, node4, node5, node6],
name2: [node1, node2]
}
Javascript uses objects and arrays. There is no multidimensional-array.
The structure you want would look like this in javascript:
{
name1: [a,b,c],
name2: [d,e,f]
}
In fact in JS, you can just define a variable with such a object like this (object literal):
var myObject = {
name1: [a,b,c],
name2: [d,e,f]
}
You do not need to iterate to construct an object in JS, object-literals are easy to understand and fast.
If for some reason you need to map some data to this new format you want, I personally would use methods such as the Array.prototype.reduce.
myMap = all.reduce(function (result, item) {
result[item.name] = (result[item.name] || []).push(item);
return result;
},{});

Using 2 arrays of objects, iterate over them using something similar to IndexOf (or other option)

I have an array of objects, i was trying to iterate over. The array is pretty simple in format.
{a:5, b:"key", c:19}
i was trying to compare an array with a subset, say: [{a:5},...]
for (var i = 0; i < subset.length; i++) {
var searchTerm = subset[i].a;
var index = objs.indexOf(searchTerm, function (el) {
return el.a;
});
if (index > -1) {
objs[index].Found = true;
}
}
So that way ultimately objs, could have a new key in it, 'Found'
This way, it will set the main array objs item.Found = true, if it existed in subset.
There are 2 issues though. Accounting for multiple instances of the same item, and the fact that this current implementation doesnt seem to work.
This is a slight expansion of (indexOf method in an object array? )but with an array of search terms.
ideally, i dont want to change the arrays at all, so im trying not to slice, etc.
In a lot of the defintions, indexOf is defined as:
function indexOf (key, start);
instead of the ideas i am trying to work with.
Edit
Here is some code that i have to get this working, but i was thinking there is a more effecient way to do it than written.
for (var j = 0; j < compare.length; j++){
var searchTerm = compare[j]["a"];
for (var k = 0; k < objs.length; k++){
if (!objs[k].Found && objs[k]["a"] == searchTerm){
objs[k].Found = true;
break;
}
}
}

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].

Javascript: Iterating over array with non-consecutive keys

I need to iterate over an array for which the keys are non-consecutive:
var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";
Obviously using the index of a for loop will not work as it depends on the keys being sequential:
for (var i=0 ; i<messages.length ; i++) {
alert(messages[i]); // Will only alert the first message, as i is never equal to 3
}
What is the canonical way of dealing with this, seeing as the for-each syntax is not intended for iterating over values in an array in javascript? Thanks.
The idiomatic way would be to use an object, not an array. Just be sure to check hasOwnProperty to make sure you don't pick up stray things which may have been added to the prototype.
var messages = { };
messages[0] = "This is the first message";
messages[3] = "This is another message";
for (var i in messages) {
if (messages.hasOwnProperty(i))
alert(messages[i]);
}
Or, the more modern way would be to use Object.keys
Object.keys(messages).forEach(prop => {
alert(messages[prop]);
});
Be sure to transpile that code with Babel if you plan on running it in older browsers like IE.
for(var i in messages)
{
console.log(messages[i]);
}
You could ignore the undefined properties...
for (var i=0 ; i<messages.length ; i++) {
if(messages[i] !== undefined)
alert(messages[i]);
}
Or use forEach, which will ignore undefined undeclared properties...
messages.forEach(function(v,i) {
alert(v);
});
Simple! if the array has regular gaps between the indices do this:
for (var i = 0 ; i < messages.length; i += gap) {
alert(messages[i]); // Will only alert the messages at the regular interval/gap
}
You can use each() jQuery method to do this.
$.each(messages, function(index, val){
alert(val);
});
From jQuery docs
each()
A generic iterator function, which can be used to seamlessly iterate
over both objects and arrays. Arrays and array-like objects with a
length property (such as a function's arguments object) are iterated
by numeric index, from 0 to length-1. Other objects are iterated via
their named properties.
When you create an array and give it values at 0 and 3, undefined values are created at 1 and 2. try this:
$.each(messages, function(i,val) {
if (val) {
alert(val);
}
});
For a use case such with the assumptions:
array.length >== 1
(i.e: an array with meaningful data in it already)
Where you are interested in the data from array[1], array[15], array[45] etc
You can do something similar to:
var array = ["you","will","become","strong","with","the","codes","padawan"];
var values = [1,5,7];
for (var i = 0; i < values.length; i++){
var cypher = values[i];
console.log(array[cypher]);
}
//will, the, padawan
Or perhaps something more meaningful such as:
for (var i = 0; i < values.length; i++){
var cypher = values[i];
aService.aFn.(array[cypher],cb);
}
//calls aService.aFn separately for each value array[1] , array[5] , array[7] passed as args

Categories

Resources