javascript Object.each is not a function - javascript

While iterating over an object i get the error,
Object.each is not a function,
Here's my code:
$("#print").click(function() {
$values = {};
$("[data-type=text]").each(function(i,e){
if($(e).val() !='') {
$values[$(e).attr('name')] = $(e).val();
}
});
console.log($values);
$values.each(function(i,e){
console.log(i.e);
});
});
moreover, i can't use for loop too, since i don't know the keys .

In your code, $values is not a jQuery Object and .each() will not work.
Iterate over a jQuery object, executing a function for each matched element.
You will want to use $.each() instead:
$.each($values, function(k,v){
console.log(k + ": " + v);
});
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.
You can also just send an Object (jQuery or not) to console:
console.log($values);

Related

JQuery - pushing elements to an array

I have the following working code:
var eachLine;
var newArray =[];
$.each(eachLine, function(){
allWordsArray.push($.trim(this));
});
But when I try to modify the above the above code like below: I am passing the variable to a function which returns a variable.
var eachLine;
var newArray =[];
$.each(eachLine, function(){
var stem = stemmer($.trim(this));
allWordsArray.push(stem);
});
It is throwing me a type error later in some other function - saying not an object while passing an object.
Could some one please point out what I am doing wrong here. Thanks in advance.
$.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.
eachLine is not an object, $.each requires an object or array to iterate which return index,key,value in callback function.

How to iterate over an Array of objects with Ext.iterate (or JS)?

I know there is plenty of answers for this question on the net, but still I can't make it work.
After a callback on a JSON POST, I'm retrieving an Array of Object.
On the console log of the browser, the array is like this :
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
where inside each object, there is stuff like :
id4blob: "1084"
so I assume the array could be like this (correct me if I'm wrong):
[{id4blob: "1084"},{id4blob: "2008"}, [...]]
The array is stored in a variable called stationsParse
I want to iterate over these values, I've found
Ext.iterate
So I did this :
Ext.iterate(stationsParse, function(key, value) {
console.log(key + value);
});
and then tried this (which seems yo be the same but in pure JS)
for (key in stationsParse) {
var value = stationsParse[key];
console.log(key + value);
}
But none is working, nothing is displayed in my console.
Still, the function is well triggered, I can see it into Chrome console, but the for is ignored.
What Am I doing wrong ?
Is this the correct way to iterate over an array of objects ?
Try something like this:
var stationsParse = [{id: 1, someproperty: 2}, {id: 2, someproperty: 101}];
Ext.each(stationsParse, function(ob){
Ext.Object.each(ob, function(property, value){
console.log(property, value);
});
});
Here I am using Ext.each to iterate over each element in the stationsParse array. Each element in that array is an object. To iterate over each property in the object I use Ext.Object.each. Both 'each' functions take the variable you want to iterate over as its first parameter and a function as its second parameter. The function will be run on each element of the array/property of the object.
If you want to use vanilla JS to loop over an array, a simple for loop will do the the trick. Access the value of each object's id4blob property using dot notation.
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].id4blob)
}
The for...in loop is generally reserved for looping over an object's properties.
Demo
I was able to make this work:
for (var i in family) {
console.log( family[i]["name"] );
}
in this tutorial on Codecademy, where family is an array of objects.
The only difference I can see is the var in front of my iterator variable i.

for in and objects inside objects

I have a json response from an API which returns an object that contains objects
something like:
{Object}->{results}->{manyObjects}
when running this:
var list = data.results.list;
for(val in list){
console.debug(typeof val);
}
the console returns strings instead of Object.
Could someone help me scan the objects?
In your code val is just the key inside the object, not the value that key points to. Try this instead:
for(var val in list) {
console.debug(typeof list[val]);
}
Though with that in mind you may want to rename val to something else.
The for in loop will return all of the property names of the list object. You must reference these properties on the object to receive a handle to them.
var list = data.results.list;
for(val in list){
console.debug(typeof list[val]);
}

Iterating an associative array with jQuery .each

Probably the most contributing factor for this question is that I am extremely sleepy right now.
I have an array, which I initiate:
var cells = [];
Then i put some values in it (jQuery objects), for example:
$("td").each(function () {
var td = $(this);
cells[td.attr("id")] = td;
});
And now my problem. This code:
$(cells).each(function (i) {
console.log(this) // firebug console
});
logs absolutelly nothing. When i changed the associative array to a normal, number index one by substituting
cells[td.attr("id")] = td;
with
cells.push(td);
It worked correctly.
Also, when I try to iterate with the for..in loop it works as expected.
for (var cell in cells) {
console.log(cells[cell]);
}
Doeas that mean that jQuery's .each method does not accept associative arrays or am I doing something wrong?
JavaScript does not have associative arrays. It has Arrays and it has Objects, and arrays happen to be objects. When you do this:
var a = [];
a['foo'] = 'bar';
..you're actually doing the equivalent of this:
var a = [];
a.foo = 'bar';
// ^--- property of object 'a'
That is to say you're actually adding a property called foo to the object a, not adding an element to the array a.
From the documentation for jQuery.each():
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.
Since you created an Array ([]) jQuery looks at its length property, and since you have not added any elements to the array (only properties on the object, remember) its length is still zero and so jQuery (correctly) does nothing.
What you want to do instead, as others have noted, is create an Object using e.g. var cells = {};. Since a non-Array object has no length property (not by default, anyway) jQuery will know that you really want to iterate over its properties instead of numeric indices as in an Array.
You seem to be thinking Javascript's arrays are associative, which is not the case. You're probably looking for objects (or hashes) instead:
var cells = {}; // Not [].
$("td").each(function() {
var td = $(this);
cells[td.attr("id")] = td;
});
$.each(cells, function() {
console.log(this); // This should work as expected.
});
use $.each(cells, function(i) { ... }) instead of $(cells).each(function...)
The $.each() function is different from the $(selector).each function.

How does jQuery.each() work with associative arrays (objects)?

I have an associative array with two object inside. Running this through $(myassoc).each(), the callback runs only once. Also the callback parameters (index and object) returns 0 and the entire associative array, respectively.
One would expect jQuery.each() to run for each element in the array, returning the correct keys as index and the correct element as the object.
Why isn't that happening, and can jQuery do what I'm after?
I think you're looking for jQuery.each() instead of .each()
try this:
$.each(myassoc, function(index, value){
//your code
});
try this:
$.each(assocarray,function(i, value){
console.log('index: ' + i + ',value: ' + value);
});
Badly.
Don't $(associative_array).each(function () {...}) -- that's nonsense
Don't $.each(associative_array, function() {...}); -- that has an obscure bug(1)
To see the bug, try this in a javascript console:
> $.each({foo:1, length:-1, bar:2}, console.log)
foo 1
length -1
bar 2
> $.each({foo:1, length:0, bar:2}, console.log)
The first example outputs three lines of key-value pairs, as it should. The second outputs nothing!
The moral of the story, don't use jQuery.each() on objects. (Objects in JavaScript are essentially the same thing as associative arrays.) Things may work fine forever, but you run the risk that someday an object happens to have a member named length and its value happens to be exactly 0 and then you have a bug out of nowhere that can be very difficult to explain. (I'll let you guess, by the ponderous heft of this answer, whether that ever happened to me.)
As mentioned in the bug report:
If you need to iterate over all keys of objects having the length property, jQuery.each is not the correct solution.
I suggest going further, that jQuery.each should not be relied upon for associative arrays, ever.
(1) This "bug" may never be fixed, since $.each() historically uses Duck Typing on arrays: "Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index."
Here's what I use[thanks Dominik] to loop through property names and values of objects, or put another way, the keys and values of an associative array:
function looper(object, callback) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
if (false === callback.call(object[key], key, object[key])) {
break;
}
}
}
return object;
}
looper() is then a drop-in replacement for $.each()
> looper({foo:1, length:0, bar:2}, console.log)
foo 1
length 0
bar 2
Just like $.each():
Inside the callback, this is each value
Inside the callback, returning false (not just falsy) terminates the loop
looper() returns the object originally passed to it
looper() works on arrays as well as objects.
Use:
var a = [];
looper({foo:1, length:0, bar:2}, function(k, v) {
a.push(k+"="+v);
});
console.assert("foo=1,length=0,bar=2" === a.join());
Try that with $.each() and you'll get an empty result. Because it interprets this particular object as an array-like object of zero length.
The problem is that the $.each() function internally retrieves and uses the length property of the passed collection. But in an associative array that has no integer indices the length always seems to be 0. For $.each() now there seems to be nothing to walk through.
The $.each() function internally retrieves and uses the length
property of the passed collection.
The solutions is simply to use an object instead.
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});

Categories

Resources