chrome.storage remove specific item from an array - javascript

This is the JSON stored in my chrome local storage
{"users":[
{"password":"123","userName":"alex"},
{"password":"234","userName":"dena"},
{"password":"343","userName":"jovit"}
]}
Is it possible to remove a specific item in "users" ?
I tried to this code but no luck
chrome.storage.local.remove('users[0]', function(){
alert('Item deleted!');
});

There is no magic syntax to delete only one element from an array that is stored in chrome.storage. In order to delete an item from the array, you has to retrieve the stored array, throw away the unwanted items (or equivalently, keep only the items that you want to keep), then save the array again:
chrome.storage.local.get({users: []}, function(items) {
// Remove one item at index 0
items.users.splice(0, 1);
chrome.storage.set(items, function() {
alert('Item deleted!');
});
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice.
Note that if you want to delete one or more items whose value satisfies a certain condition, you have to walk the array in reverse order. Otherwise you may end up removing the wrong items since the indices of the later elements are off by one after removing the first item, off by two when you've removed two items, etc.

Yes you can try this
chrome.storage.sync.remove("token");
see documentation

Related

mongodb: atomically remove first n elements of array

I want to atomically remove the first n elements of an array field.
Right now, I use model.find(), then doc.arrayField.slice(n), then doc.save(). But this loads the entire document in memory (bad if document is very large), and it would kill the atomicity.
Is there a way to achieve this atomically in MongoDB/Mongoose?
Thanks!
You can use $pop to remove first element atomically. Or if you can specify which fields to remove you can use $pull to remove multiple items from an array. Otherwise you cannot remove first n elements from array in an atomic operation using mongodb.
db.yourCollection.update({}, {$pop: {arrayField: 1}}}) // will remove the first element from arrayField
db.yourCollection.update({}, {$pull: {arrayField: {foo: "bar"}}}}) // will remove all elements whose foo field equal to bar from arrayField.
MongoDB provides $slice operator for array updates. https://docs.mongodb.org/v3.0/reference/operator/update/slice/
You can use in Mongoose updateClause too.
Instead of loading all arrayField data in memory, you can use $slice to project docs with first n elements of arrayFields like this
model.find({}, {arrayField : {$slice: n}}) // n is first n elements
Now you can remove those n elements using
doc.arrayField.slice(n);
doc.save();

Javascript Delete item on sparse array and adjust length error

I have a sparse Array.
I use delete array[id] and I also want to adjust the length of the array after deletions. This is a pseudocode.
....
deleted =0;
...
if (condition) { delete array[id]; deleted++;}
...
array.length-=deleted;
Ok. I dont know what happen, the array has the expected length but ... it is empty!
Any idea what is happen?
Right way to delete an element from sparse array is :
arr.forEach(elm,index){
//delete index element
delete arr[index]
}
This removes the element but leaves the array size same
If you really want to do it manually and don't care about the order of items, the following is much faster than splice, but this messes up your order:
array[id] = array[array.length-1]; // copy last item to the index you want gone
array.pop(); // rremove the last item
The length of the array is automatically correct.
If you want to keep your order do what zerkms said and use splice
array.splice(id, 1);
The first parameter is the index from where you start. The second parameter is how many items you delete.
The length of the array is also correct.

How can I search array index of xml data for a matching string?

Hi I have an array of xml data. Each array index contains a product element; the product element has child elements such as name, price etc. I output the contents of the array to a table where it is displayed and this works fine. I now want to be able to display certain manufacturers on the click of a checkbox(remove them when clicked) so what I am trying to do is access my global results array, loop through each index and within each index find the 'make' element and check if that contains the matching text. If it does match remove that index entirely from the array and out put the remaining array. I'm looping through the array using an each function but I can't seem to find a match. Does anyone have any advice thanks?
Below is my checkbox code. Once checkbox is checked loop through the array results and find
make text node.
if the text matches the target word alert but it doesnt find it.
if ($("#activision").is(':checked')){
$.each(results, function() {
var check = $(this).find('make').text();
var word="activision";
if(check==word){
alert('found');
}
And a brief look at creating my results array.
For each product element in xml push onto array.
results.push({
productname: $(this).find('productname').text(),
verdict: $(this).find('verdict').text(),
description: $(this).find('description').text(),
price: $(this).find('price').text(),
make: $(this).find('make').text(),
date:yyyymmdd,
rating:$(this).find("rating").text(),
image:imageurl,
page:sitepage,
});
I got it solved it was a mix up with syntax like I thought it was. The solution is simply
$.each(results, function() {
if(this.make=="activision"){
alert('found');
}

Stop collection from sorting itself but still able to sort i

I have a problem, I seeked help in #documentcloud on Freenode and got some suggestions but still hasn't helped me fix my problem.
Basically I have a collection, very large up to 2-3 thousand items, and it -has- to be sorted, however it only has to be sorted at certain times. Using a comparator function is fine, it keeps it sorted, but takes a lot longer when all the items are being added to the collection, as it's resorting the entire collection each time one of the 2-3000 items are added.
I've tried a couple of suggestions, one being:
collection.comparator = function(object) { object.get('sortBy'); };
collection.sort();
collection.comparator = undefined;
This fails miserably and doesn't sort at all, I've also tried using collection.sortBy(...) this seems to return the sorted collection, but it is of no use to me as when I try collection = collection.sortBy(...) it just dumps the sorted collection as an array into the variable collection. When I try to use collection functions or utilities I get errors like .each is undefined for collection, etc.
Any ideas?
This can't be done simply because Collection.sort actually calls Collection.comparator.
You have basically three options
Option One
You could force your sort method without comparator to the models itself ( basically the same as calling .sort of your collection, but without .comparator
// in your collection class
_comparator: function(a,b) { /* comparator code */ }
sorter: function() {
// Of course you should bind this to your collection at this function
// and your comparator
this.models.sort( _comparator ) // .models gives you the array of all models
}
Option Two
Remove comparator each time you add something to the collection
_comparator = function(a,b) { /* comparator code */ }
collection.comparator = undefined
collection.fetch({ success: function() { collection.comparator = _comparator })
Options Three
If you think a little bit ahead of your code, and simply want your collection sorted only because you want to display it this way, you could simply sort it on display
collection.returnSorted = function () { return collection.sortBy( _comparator ) }
Try this:
collection.add(model, {sort: false});
Would it work to use _.sortedIndex() when individual items are added to the already sorted list?
You could easily figure out the sortedIndex, slice the list based on that index, then splice: part1 + new_entry + part2.
This keeps you from sorting the entire list every time. You're just inserting one new entry in the right spot.
My answer assumes you're already able to do an initial sort of the 2000+ item collection, and that you're just trying to overcome the issue of resort when new items are added one at a time. Your question lacks specificity about exactly where your issue is though.

How can I remove an element from an array with javascript / jQuery?

I am setting an element in an array like this:
dialogs[id] = $.modal({
title: "Admin",
closeButton: true,
content: content,
width: false,
resizeOnLoad: true,
buttons: {
'Close': function (win) {
win.closeModal();
}
}
}).find('form') // Attach logic on forms
.submit(formSubmitHandler)
.end();
Later on I check if exists like this:
if (!dialogs[id]) {
loadAndShowDialog(id, link, url);
}
How can I remove the id record from the dialogs array? Is there something like a dialogs[id].Remove() ?
the command is : (set it to undefined)
delete dialogs[id];
if you want to completely remove : use splice.
edit
I mistakely thought that its is an object property which you want to remove ( delete will be fine here - and only solution)
howevert - you have an Array and the correct answer is to use splice.
I suggest you take a look at this tutorial. It explains really well how to play with arrays in javascript.
The delete method doesn't delete an element, it just replaces it with undefined. To delete elements from an array, you need splice.
According to MDN, here is how to use it:
array.splice(index , howMany[, element1[, ...[, elementN]]])
So, you need the index where you want to start deleting, and howMany is the number of elements you want to delete.
For your case, it'd be:
dialogs.splice( dialogs.indexOf( id ), 1 )
Note the use of indexOf to find out the index of the id value.
when removing an item from an array, use splice
dialogs.splice(id,1); //remove "1" item starting from index "id"
note that this removes the item, and changes the array length. so in an array of 3, if i spliced this way, the array will now have a length of 2.
using delete will not affect the array, but leave that location undefined. it's like "unsetting" or "leaving a hole" in that location.
delete dialogs[id]; //value at index "id" is now undefined
You can use
delete dialogd[id]; //will not remove element, will set it to undefined
or
dialogs.splice(id,1); //will not work in case of non-numeric indices
Choose whichever one is appropriate. I prefer the second.

Categories