I orginally was going to ask a question on why it wasn't working. But as I commented the code I realized that I could access the text array style and item was giving me the index. It took me a while to find this as the solution, however I would have much rather used item.text in the for loop. Is this [my posted answer] the valid way to loop through JSON objects in Javascript?
There's no such thing as a JSON object - once you've parsed your JSON (which is a string) you end up with simply an object. Or an array.
Anyway, to loop through an array of objects, use a traditional for loop. A for..in loop may work, but is not recommended because it may loop through non-numeric properties (if somebody has been messing with the built-in array).
In your specific case, if obj.body.items is an array then do this:
for (var i = 0; i < obj.body.items.length; i++) {
// obj.body.items[i] is current item
console.log(obj.body.items[i].text);
}
You can also, arguably, make the code a bit neater by keeping a reference directly to the array rather than accessing it via the whole obj.body. chain every time:
var items = obj.body.items;
for (var i = 0; i < items.length; i++) {
console.log(items[i].text);
}
"I would have much rather used item.text in the for loop"
In your answer - which really should've been posted as part of the question - because you are using a for..in loop your item variable is being set to each index in turn as a string, e.g., on the first iteration it will be the string "0", and strings don't have a text property so item.text doesn't work - although it should give you undefined, not null. But you can do this:
var item;
for (var i = 0; i < obj.body.items.length; i++) {
item = obj.body.items[i] // get current item
console.log(item.text); // use current item
}
That is, declare a variable called item that you set to reference the current array item at the beginning of each loop iteration.
<script type="text/javascript">
...
obj = JSON.parse(xmlhttp.responseText);
// displays the object as expected
console.log(obj);
// display the string next as expected
console.log(obj.body.next);
// displays the text of the item as expected
console.log(obj.body.items[0].text);
for (var item in obj.body.items) {
// displays the index value of the item
console.log(item);
// displays null - WHAT?? HUH?
console.log(item.text);
// displays the text - finally
console.log(obj.body.items[item].text);
}
<script>
Related
I have an array of 11 objects which contain JSON data. I wrote a function in which a new key with a zero value is added to each of the objects. Now I want to update the value of the said key in all 11 objects. The data is stored in an array2 with 11 numbers. My for loop doesn't seem to work for this, and the only way to do it (so far) is to hard code it. Does anyone has a suggestion how this can be done?
The desired outcome would be this:
array[0].new_key = array2[0];
array[1].new_key = array2[1];
The first art of the function, before the for loop with j, is for adding the new key into the original array and that part works.
for (i = 0; i < array.length; i++) {
array.map(i => i.new_key = 0);
console.log(array)
for (j = 0; j < array2.length; j++) {
array[i].new_key = array2[j];
console.log(array)
}
}
}```
I split it into two functions, I realized that I made it too complicated and it didn't made sense. I wrote a second function that only updates all the key values, so indeed, I removed the inner loop as it was not needed. Thank you for the help.
.map() does not modify the original array:
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
You will want to get the result of the map by assigning it to a variable, and see what is happening there. Right now you don't do anything with it, so it will just disappear.
While the above is true for maps, in this case the original array is being modified as we access the object's properties and modify them there.
I'm facing a javascript problem with deleting items in an array within a for loop.
My code is checking the existence of a localStorage item containing a stringified object, parse it, run the for loop, do some stuff (that works great) on each item, delete the item if conditions are good, and finally save the new array to the localStorage item.
Here it is :
if (localStorage.getItem(user_id+"_tosave") && localStorage.getItem(user_id+"_tosave").length>1){
var local_tosave = JSON.parse(localStorage.getItem(user_id+"_tosave"));
if (local_tosave.length>0){
for (i = 0; i < local_tosave.length; i++) {
// SOME OTHER STUFF HERE...
if (navigator.onLine){local_tosave.splice(i,1);}
};
localStorage.setItem(user_id+"_tosave",JSON.stringify(local_tosave));
alert(localStorage.getItem(user_id+"_tosave")); // DISPLAY TO CHECK
}
}
Only the last item of the array is deleted... why is that ? The splice function breaks the loop when there's more than one element in the array.
I guess there's something about object & iteration as i saw in other conversations but the solutions given didn't work for me.
Fyi, i tried local_tosave.splice(i--,1); which was even worse.
Thanks for your help.
I would try to walk array backwards, if order doesn't matter. Like this
for (i=local_tosave.length-1; i>=0; i--) {
so the elements on the end would be chopped off and the rest of array would be untouched.
hope it helps
The problem is in the increment. I suggest to use an other loop with while.
var i = 0;
while (i < local_tosave.length) {
if (navigator.onLine) {
local_tosave.splice(i, 1);
continue; // because i should stay
}
i++;
};
This is something very basic I might be missing here but I haven't seen such result till now.
I have a for loop where options.headers.length is 3. And in for loop I am dynamically creating a table header. Ideally this loop should run three times for 0 1 and 2 but when I have printed index it's printing 0,1,2,clean and remove. I haven't seen clean and remove as indexes. I know this information is not sufficient enough but if you have any clue please suggest. something might be overriding this is all I am concluded too after my debugging.
for (index in options.headers)
if you don't want to iterate clean and remove then change the loop to:
for (var i=0; i< options.headers.length;i++){
//use i for getting the array data
}
if you use for (index in options.headers) it will iterate for non-numeric keys also.
don use just index (as that is = window.index = global = bad) use var index
(read more here https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=globals+javascript+bad)
you have to check does the array has it as own property or maybe its some function (more after answer)
for (var index in options.headers) {
if (options.headers.hasOwnProperty(index) {
// code here
}
}
more about #2:
let's say we have
var array = [0,1,2,3];
and besides that, extending array with function (arrays can have functions in javascript and strings too)
Array.prototype.sayHello = function() {
alert('Hello');
};
then your loop would print sayHello as part of the array, but that's not it's own property, only the arrays
I assume that options.headers is an Array?
This happens when you (or some framework you load) adds methods to the Array prototype. The "for in" loop will enumerate also these added methods. Hence you should do the loop for an array with:
for (var i = 0; i < options.headers.length; i++)
That way you will only get the real values instead of added methods.
This should be very easy but I don't know how to do it.
I have this object:
var obj = eval(result);
Now I want to know how many properties contains to put it in a loop
var finalAmount = obj.length;
Now I go for the loop
for (var i in obj) {
--- some other code in here
Now here the problem I need to do something when the loop reaches the final property of the obj, so this is what Ive tried:
if (i+1 == finalamount){
//do something
} else {
//do something else
}
so basically using the i as a pointer to compare it to the var that contains how many items there are and when finding the final one of the loop then do something...
In this case i is not necessarily numeric, and so i+1 may not give you the desired results. You should set up a separate counter variable that you increment at the end of each loop iteration.
In your case obj must be an Array. If it is not, i+1 throws error.
The for-in loop does not ensure any sequence order, even it is an Array, it is only used to iterate unordered properties. You need traditional for(index=0;index<length;index++) (if it is an Array)
If your obj variable is an Object instead of Array, you can't get "last property" only with object data structure, it must provide more information (property order).
As per what I know, arrays in Javascript is nothing but the combination of methods and objects.
Now my task is to display the values of array (say y_array)
I have used for(x in y_array) and then displayed the value.
In mozilla and in IE its working fine, but in IE it displays the first element of array with index as indexOf and value is indexOf(obj, from) which i dont want.
I tried
if(x!='indexOf') { display the array value ; }
It worked and things were fine but there is extensive use of arrays been displayed and I am looking for some permanent fix rather than this hardcoded one.
Can anyone please help me?
You are not the first mixing up arrays and objects. SO should contain a FAQ for this kind of questions ;)
Let's try to explain things:
An array is a row of values, which can be retrieved using their position in the row. The order of the array values is fixed (and may be reordered).
An object is a variable that contains named properties in the form of key-value pairs. The order of the key-value pairs belonging to an object is arbitrary.
An array looks like: [ 'first', 'second', 'third', ..., 'nth' ]
An object looks like: { first:'firstvalue', second:'secondvalue', ..., nth:'nthvalue' }
The first element of an array is the element with index 0 (so the first position in the row has index value 0). You retrieve it using myArray[0]
An object is unordered, so it has no first element. You retrieve any element from it using myObject.somekey or myObject['somekey'].
For arrays you use a loop iterating through the numbered index until the end of the array is reached:
var i=0, len = myArray.length;
for ( i; i<len; i++ ) {
//do something with >>> myArray[i] <<<
}
For objects you use a loop using the key and the in operator (making sure you are only retrieving user defined properties of the object with the .hasOwnAttribute method):
for ( var key in myObject ){
if (myObject.hasOwnProperty(key)) {
// do something with >>> myObject[key] <<<
}
}
Basically, think of an array as a cupboard with drawers, each containing a value. An object can be imagined as a pile of boxes with stickers on the lid, describing the content of the box. Retrieving something from an object, you ask: is there a box with sticker y in pile x and if so, what's in it? Retrieving something from an array, you ask: please give me the contents of drawer nr x.
Now as to your question: the array you are retrieving values for with a for..in loop contains a user defined method, namely indexOf. Using the object style loop for it, the array is treated as object, and the indexOf key (with value like function(){...} I bet) is shown too. IE That's why it may be better to use a traditional for loop with a numeric index when iterating over arrays.
Why is this only in IE? In modern browsers indexOf is a native method of the Array prototype, and native methods are not shown (unless you loop through their prototype that is). IE < 9 doesn't have a native indexOf method for arrays. Somewhere in the scripting you use the method has been added to the Array prototype as a user defined extension.
Bottom line for your problem: don't use for ... in to loop through the values of an array.
For arrays you should use this for loop:
var y_array = [1,2,3,4];
for (var i = 0; i < y_array.length; i++) {
var value = y_array[i];
// do what you want
alert(i + ': ' + value);
}
For objects (objects are like associative arrays - property: value) use this loop:
var y_array = { prop_1 : "value a", prop_2: "value_2", prop_3: 333 }
for (var key in y_array) {
var value = y_array[key];
// do what you want
alert(key + ': ' + value);
}
if there is no value in your json Object like jsobObj = {}. Then you got the indexOf prototype function in side the empty object in IE < 9. (with value like function(){...} I bet) is shown too.
Your can check a condition in side your for Loop. and skip that indexOf.
if(key =='indexOf'){continue;}
E.g :
var jsonObj = { key_1 : "value a", key_2: "value_2", key_3: 333 }
for (var key in y_array) {
if(key == 'indexOf'){continue;} // check if the array contain indexOf
var value = y_array[key];
// do what you want
alert(key + ': ' + value);
}