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++;
};
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 am trying to add data to localStorage, it's a multi-dimensional array.
In order to "append" data to the array, I'm pulling it from localStorage with .getItem, using array.push to add my new data, and then resetting it with .setItem
The array data looks a little like this:
var wishlist = [
["210 Derby Road","http://localhost:8888/properties/210-derby-grove/"]
]
This works fine my only problem is not adding the data twice, so I need to search the array and see if it's present.
I tried first simply using the jQuery utility function:
console.log($.inArray(name, wishlist));
name in this case is 210 Derby Road so it should return true. This returned -1 even when the data was present.
I figured maybe because this is a multi-dimensional array that I needed to loop through the sub-arrays instead, so I created a for loop:
for (var i = 0; i < wishlist.length; i++) {
console.log($.inArray(name, i));
}
I'm still getting -1 returned.
How can I check my array wishlist to see if name is present?
JSFiddle
You almost got it right! Use:
for (var i = 0; i < wishlist.length; i++) {
console.log($.inArray(name, wishlist[i]));
}
cause wishlist[i] is the current Array.
Than to get a boolean do like:
if($.inArray(name, wishlist[i]) > -1) { /* do something*/ }
You can do with pure JS method Array.prototype.includes().
wishlist.findIndex(f => f.includes(name)) === -1 && // push it.
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.
I tried this but doesn't help. For loop doesn't iterate even once.
for(var i = 0; i < $scope.recordList1.length; i++) {
delete $scope.recordList1[i].attributes;
}
JSON:-
[{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6yAAA"},"Name":"Stella Pavlova","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6yAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6zAAA"},"Name":"Lauren Boyle","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6zAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt70AAA"},"Name":"Babara Levy","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt70AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt71AAA"},"Name":"Josh Davis","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt71AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt72AAA"},"Name":"Jane Grey","Phone":"(520) 773-9050","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt72AAA"}]
You're saying the for loop doesn't iterate. Does the length positive? Maybe you are looping on the data before it was filled. Try to log the array length and see. Maybe your data is overwritten somewhere.
Anyway, you could use the array method forEach - that way you don't need the i counter.
arr.forEach(function(value){
delete value.attributes;
});
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>