I'm trying to build 'wishlist' functionality. When you click a button, it saves the name and link for the particular 'property' in an array in local storage. I will then output this on the page for the user.
So far it works, my only problem is that it will always insert the property name and link, even if it's already present in the array. I need to create a check, to see if it's already there, and only push it if it can't be found.
Here's a JSFiddle that works. Click the "save" buttons and check localStorage and you will see that the data is added. But click the same button again and you'll see it's added, again.
https://jsfiddle.net/g9kkx3fh/3/
Here's the basic code. It grabs the property name and link from the closest clicked button, it pulls data back from the array in localStorage, then uses .push to add the new data, then re-stringifys it and adds it back to localStorage.
var name = $(this).closest('.text-long').find('.intro-text h4').text();
var permalink = $(this).closest('.text-long').find('.button-slot a').attr('href');
var property = [name, permalink]; // create an array of the name + permalink
var wishlist = JSON.parse(localStorage.getItem("wishlist")); // get the wishlist from storage
wishlist.push(property); // append the new array into the wishlist from storage
localStorage.setItem('wishlist', JSON.stringify(wishlist)); // put the wishlist back in storage
I knew I needed to iterate over the array, being multi-dimensional, and look for the same name var. So I started with this:
for (var i = 0; i < wishlist.length; i++) {
var isPresent = ($.inArray(name, wishlist[i]));
}
if (isPresent == -1){
wishlist.push(property);
localStorage.setItem('wishlist', JSON.stringify(property));
}
Here's the problem with this. If the localStorage var wishlist is empty, then its length is 0. Therefore the for loop never works, because i < wishlist.length is never true, because wishlist is always 0.
So how do I fix this? I'm never able to add anything to the array, because I can never get the value of isPresent, because my for loop never works.
Here's a JSFiddle for the broken code, but with the for loop and if statement added:
https://jsfiddle.net/bdxa0sgz/1/
I've also tried the following:
if (isPresent == -1 || wishlist.length == 0){
...
}
So that if the wishlist is empty, it'll still run. However this seems to jumble together the name data and overwrite the array. I'm very confused.
https://jsfiddle.net/bdxa0sgz/5/
Before you push the property array to the wishlist array you have to check if wishlist contains it right. So you might simply do it like this. Let's invent a generic Array.prototype.compare() method. However since this is going to be a generic method it also takes care of the possibility of array elements being objects. So we have an Object.prototype.compare() too (in this case we don't need it but it's good to know) So here is the code;
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
Array.prototype.compare = function(a){
return this.every((e,i) => typeof a[i] === "object" ? a[i].compare(e) : a[i] === e);
};
var button1 = ["29 Melton Road32 York Road","http://localhost:8888/test-properties/properties/29-melton-road/"],
button2 = ["32 York Road","http://localhost:8888/test-properties/properties/32-york-road/"],
wishlist = [],
push2wl = btn => wishlist.some(a => a.compare(btn)) ? wishlist : wishlist.concat([btn]); // if exists return wishlist untouched
wishlist = push2wl(button1);
wishlist = push2wl(button2);
wishlist = push2wl(button1); // this won't get inserted
wishlist = push2wl(button2); // this won't get inserted
console.log(wishlist);
I use arrow functions but you may replace them with their conventional counterparts if you want to see your code work on Safari 9 or IE.
Use Map (key, value) pair to store your properties so that you can check using
myMap.get(key)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
Here, have a look at this detailed article: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
For your example,
var myMap = new Map();
$('body').on('click', '.icon.heart button', function(e) {
var name = $(this).closest('.text-long').find('.intro-text h4').text();
var permalink = $(this).closest('.text-long').find('.button-slot a').attr('href');
var property = [name, permalink];
console.log(property);
if (myMap.get(name) === null) {
var wishlist = JSON.parse(localStorage.getItem("wishlist"));
console.log('Wishlist from localStorage = ' + wishlist);
wishlist.push(property);
console.log(wishlist);
localStorage.setItem('wishlist', JSON.stringify(wishlist));
myMap.set(name, permalink);
}
});
You can also iterate through the map to get all the properties like this:
var mapIter = myMap[Symbol.iterator]();
console.log(mapIter.next().value);
I hope this works for you.
Related
I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.
I have a simple button that removes an item from a json object. This is currently working fine. The issue I have is that once it's clicked once it doesn't work again due to a js error. The error is reporting that an item is null.
I thought delete would remove the json item, not simply mark it as null.
See this JSFiddle
$("button").click(function() {
var jsonObj = $.parseJSON($('div').text());
var name;
if($(this).attr('id') == 'btn1') name = 'John2';
if($(this).attr('id') == 'btn2') name = 'Anna';
$.each(jsonObj, function(i, obj) {
if (obj.firstName == 'Anna') delete jsonObj[i];
});
$('div').text(JSON.stringify(jsonObj));
});
I need to get the json text from the div, remove an item from it, then save it as text back to the div. Any help would be appreciated.
you should be iterating over the .employees array element of the object
you can't delete an element from an array with delete - use .splice instead.
you should return false from the $.each callback once a match has been made, or you'll end up iterating over non-existent elements - you must always be careful when modifying the size of a collection whilst iterating over it.
See https://jsfiddle.net/alnitak/mjw4z7jL/1/
The reason is because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.
Use for loop instead of $.each or return false once you are inside the condition.
$("button").click(function() {
var jsonObj = $.parseJSON($('div').text());
var name;
if($(this).attr('id') == 'btn1') name = 'John2';
if($(this).attr('id') == 'btn2') name = 'Anna';
for(i=0; i < jsonObj.employees.length; i++){
if (jsonObj.employees[i].firstName == name){
jsonObj.employees.splice(i,1);
}
}
$('div').text(JSON.stringify(jsonObj));
});
https://jsfiddle.net/bipen/715qkhwo/4/
Remind you, this is not a proper solution and depends entirely on how your json object is. If there are two objects with same firstName, this might give you weird result. So make sure you add all of the needed condition before you delete it.
You were iterating through the root object, it has one single property, employees
You needed to loop through object.employees array
Far easier with native array filter function
Note: This will handle multiple Johns and Annas without issue
$("button").click(function() {
var jsonObj = $.parseJSON($('div').text());
var name;
if(this.id == 'btn1') name = 'John2';
else if(this.id == 'btn2') name = 'Anna';
else return;
jsonObj.employees = jsonObj.employees.filter(function(emp) {
return emp.firstName != name;
})
$('div').text(JSON.stringify(jsonObj));
});
https://jsfiddle.net/715qkhwo/5/
I'm trying to set objects into localStorage with a format similar to the following:
[{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]
Where I'd be able to set the 1 or 2 based on a dynamic value I'm getting from a REST call. What I have so far is:
// check if session exists and create if not
var StorageObject = JSON.parse(localStorage.getItem("session")) || [];
//see if the current id from the REST call is in storage and push with properties if not
if ( !StorageObject[thisItemsListID] ) {
var itemProperties = {};
itemProperties[thisItemsListID] = {};
itemProperties[thisItemsListID]["property1"] = false;
itemProperties[thisItemsListID]["property2"] = false;
StorageObject.push(itemProperties);
localStorage.setItem('session', JSON.stringify(StorageObject));
}
I can get the data into localStorage using this format but StorageObject[thisItemsListID] always gets into the if statement and generates a duplicate item in localStorage and I'm not sure how to access this with a variable. I'm trying to append the new ID if it doesn't exist so if {1:{} exists but current ID is 2 I need to push the new value.
I'm close here and maybe I need to reevaluate the format I'm storing the data string but I'm going in circles here and could use a point in the right direction.
Well, the duplicate item is happening in StorageObject.push(itemProperties).
Try this to update the object:
//StorageObject.push(itemProperties); <-- remove
StorageObject[thisItemsListID] = itemProperties;
[EDIT]
If you want to keep [{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]. To conditional would be a bit different.
var haveItem = StorageObject.filter(function(item){
return Objects.keys(item)[0] == thisItemsListID;
}).length > 0;
if ( !haveItem ) {
var itemProperties = {};
itemProperties[thisItemsListID] = {};
itemProperties[thisItemsListID]["property1"] = false;
itemProperties[thisItemsListID]["property2"] = false;
StorageObject.push(itemProperties);
localStorage.setItem('session', JSON.stringify(StorageObject));
}
Are you trying to update the object or just overwrite it? Filipes response illustrates how to update the entire storage object by just reassigning the object with the new value.
If you wanted to update just as section/ value of the object you could do so using a for loop. This would allow you to scan the array locate the one property and then remove it, updated it, overwrite it etc.
Here is an example of the loop. Bear in mind This is a snippet from a report library I was building. It uses angular $scope but it is a complex type doing a similar action to your update (here I am setting a label as a favorite/bookmark)
function OnFavoriteComplete(response) {
var id = response.config.data.reportId; //dynamic values set by client
var isFavorite = response.config.data.isFavorite;//dynamic values set by client
var arrayCount = $scope.reportList.length;
//loop my current collection and look for the property id of the label
//then check to see if true or false/this was a toggle enable disable
if (isFavorite) {
for (var i = 0, iLen = arrayCount; i < iLen; i++) {
if ($scope.reportList[i].reportId == id) {
$scope.reportList[i].isFavorite = false;
}
}
}
//if false update the property with the new value
else {
for (var i = 0, iLen = arrayCount; i < iLen; i++) {
if ($scope.reportList[i].reportId == id) {
$scope.reportList[i].isFavorite = true;
}
}
}
};
If you are using another framework like lowDash it has some really nice helper functions for updating and evaluating arrays.
In my Notes Database, I perform an audit when the document is saved. Pretty easy in LotusScript. I grab the original document (oDoc) from the server, then in the document I modified (mDoc), I do a Forall loop that gets the names of each item; forall item in mDoc.items. Grab the same item from oDoc, execute a function with the new item as an argument that will run down a case statement that will see if its a field we care about. if so, I update a set of list values in the document with "When", "Who", "What field", and the "New Value".
I'm doing this in a server side script. In trying this, I discovered a couple of interesting things;
currentDocument is the NotesXSPDocument that contains everything that was just changed.
currentDocument.getDocument() contains the pre-change values. It also returns a NotesDocument which has the "items" field that I can run through.
Thing is, I need something similar in the NotesXSPDocument. Is there a way in an iterative loop to grab the names and values of all items from there?
Here's the broken code. (Currently it's walking through the NotesDocument items, but those are the old values. I'd rather walk down the XSP document items)
function FInvoice_beginAudit() {
var original_doc:NotesDocument = currentDocument.getDocument();
var oItem:NotesItem;
var oItems:java.util.Vector = original_doc.getItems();
var iterator = oItems.iterator();
while (iterator.hasNext()) {
var oItem:NotesItem = iterator.next();
item = currentDocument.getItemValue(oItem.getName());
if (oItem == undefined) {
var MasterItem = ScreenAudit(doc,item,True)
if (MasterItem) { return true }
} else {
if (item.getValueString() != oItem.getValueString()) {
var MasterItem = ScreenAudit(doc,Item,True);
if (MasterItem) { return true }
}
}
}
}
You can get both versions of a document after submit - the original and the one with changed/new values:
original: var original_doc:NotesDocument = currentDocument.getDocument();
changed: var changed_doc:NotesDocument = currentDocument.getDocument(true);
This way you can compare the items for changes.
But, there is a pitfall: after assigning "changed_doc" to currentDocument.getDocument(true) the "original_doc" has the changed values too because both variables point to the same document. That's why we have to copy all items from currentDocument.getDocument() to a new temporary document first and only after get the changed values with currentDocument.getDocument(true). As an alternative you could read the original document from server like you do in LotusScript.
This is a code for detecting changed items as a starting point:
var original_doc:NotesDocument = database.createDocument();
currentDocument.getDocument().copyAllItems(original_doc, true);
var changed_doc:NotesDocument = currentDocument.getDocument(true);
var oItems:java.util.Vector = original_doc.getItems();
var iterator = oItems.iterator();
while (iterator.hasNext()) {
var oItem:NotesItem = iterator.next();
var itemName = oItem.getName();
var cItem:NotesItem = changed_doc.getFirstItem(itemName);
if (cItem.getText() !== oItem.getText()) {
print("changed: " + itemName);
}
oItem.recycle();
cItem.recycle();
}
original_doc.remove(true);
original_doc.recycle();
I have an application where I am adding li elements to the web page. I need to change the class name of the element to "done" inside of local storage when I mark it as "done" on the webpage. (It should say done: true). With my current code I am unintentionally making two items in local storage, one which is done: true and the other which is done: false. I'll show my code here:
function updateDone(e) {
var spanClicked = e.target;
var id = spanClicked.parentElement.id;
var done = spanClicked.parentElement.className;
spanClicked.innerHTML = " ✔ ";
spanClicked.setAttribute("class", "done");
var key = "todos" + id;
for(var i = 0; i < todos.length; i++) {
if(todos[i].id == id) {
var mark = todos[i];
mark.done = true;
console.log(mark);
spanClicked.setAttribute("class", "done");
var newKey = JSON.stringify(mark);
localStorage.setItem(key, newKey);
if(mark.done == false) {
spanClicked.setAttribute("class", "not done");
spanClicked.innerHTML = "not done";
}
}
}
}
They are both labeled with the same id which is how I keep track of each item, yet there are two of them. Also, when i refresh the page there are two list items shown, one which is marked done. My question is how do I prevent another item from being created and instead mark just one item as done in localStorage?
You need a way to uniquely identify each item, so you can ensure your marks are being set on the items you intend and are not overwriting because you might have, say, two items with the same key. Since you are looping through a list, maybe you can change your keys to be composed of two parts.
var parent_key = "todos" + parent_id;
And then, in the loop :
var store_key = parent_key + ":" + i;
...
localStorage.set(store_key,newKey);
This way (so long as the order is going to be consistent), you can separate multiple list elements from the same parent.
As commented, a live example in jsFiddle or something would help better address your requirement.
However if this solution is insufficient you could try the following idea, effectively setting a "table" within localstorage.
var parent_key = "todos" + id;
var parent_table = {};
// for loop
parent_table[i] = newKey;
// end of for loop
localStorage.set(parent_key,parent_table);
So you have a table inside of local storage, to give you finer granularity.