I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.
I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;
// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
recordCounter.innerHTML = (count = 0);
}
function addNameRecord() {
resetNotify.innerHTML = '';
var name = document.getElementById('names-field');
nameArray = JSON.parse(st.getItem('names'));
count = Number(count) + 1;
newArr = makeArr(nameArray);
// Check if there is anything in the name array.
if (nameArray != null) {
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
nameArray = [];
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}
st.setItem("names", JSON.stringify(nameArray));
name.value = '';
if (!newArr[0]) {
count = 1;
theLIst.innerHTML = nameArray;
recordCounter.innerHTML = count;
} else {
theLIst.innerHTML = newArr[0].join('');
recordCounter.innerHTML = count;
}
}
// Take our string from local storage and turn it into an array we can use
function makeArr() {
return Array.from(arguments);
}
// Purge all entries, reset counter
function clearArray() {
st.clear();
nameArray = [];
theLIst.innerHTML = '';
recordCounter.innerHTML = (count = 0);
resetNotify.innerHTML = 'Array has been purged.';
}
Heres the code I tried
// Delete a specific entry
function clearThisItem(item) {
console.log(item);
localStorage.removeItem(item);
console.log(localStorage.removeItem(item))
return item;
}
Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
After every action just update the UI using a single function call.
Note: Renamed names-field to name-field in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){
setNames([]); // initializing the empty array for first time.
}
renderData(); // display data
function addNameRecord() {
$resetMessage.innerHTML = '';
var name = document.getElementById('name-field');
addName(name.value);
renderData();
name.value = ''; //clear input field
}
function renderData(){
var names = getNames();
$resetCouter.innerText = names.length; // Count
var namesListHTML = '';
names.forEach(function(name, index){
namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
});
$list.innerHTML = namesListHTML;
}
function clearArray() {
setNames([]); // clear names
$resetMessage.innerHTML = 'Array has been purged.';
renderData();
}
function clearThisItem(name){
removeName(name); // remove from localStorage
renderData();
}
function getNames(){
namesStr = localStorage.getItem('names');
if(namesStr) {
return JSON.parse(namesStr);
}
return null;
}
function setNames(names){
return localStorage.setItem('names', JSON.stringify(names));
}
function addName(name){
var names = getNames();
names.push(name);
setNames(names);
}
function removeName(name){
var names = getNames();
var index = names.indexOf(name);
if (index > -1) {
names.splice(index, 1);
}
setNames(names);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Count : <span id="record-counter"></div></p>
<input id="name-field">
<button onclick="addNameRecord()">Add</button>
<button onclick="clearArray()">Clear</button>
<div id="list"></div>
<div id="reset-message"></div>
</body>
</html>
Use localStorage.removeItem(insertYourKeyHere); to remove an object from local storage.
For removing it from your nameArray you can search through your list for the record, set null and then sort your list by ensuring to move objects into new positions such that null is at the end, then decrement your count for the number of records
I'm using fabricjs and want to render the text every time a value is updated.
But when I do this, the new text overlaps the old. I tried to clear the object but didn't find any way to do so.
Below is the code snippet to describe what I doing:
//console.log('topp'+ rect.getTop());
rect.on('moving', function() {
var rectTop = rect.getTop();
var upCounter = 0;
var downCounter = 0;
var text40;
var canvas_objects = canvasForRect._objects;
// console.log('topp'+ rect.getTop());
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('heatMapClickData');
// CONVERT STRING TO REGULAR JS OBJECT
var text40;
var last = canvas_objects[canvas_objects.length - 1];
var parsedObject = JSON.parse(retrievedObject);
$.each(parsedObject, function(index, item) {
if (rectTop >= item['pos_y']) {
upCounter += 1;
} else {
downCounter += 1;
}
text40 = new fabric.Text("Total clicks above line" + upCounter, {
fontSize: 40
});
});
// var obj = canvasForRect.getActiveObject();
// console.log(obj);
text40.set({
text: "Total clicks above line" + upCounter
});
canvasForRect.add(text40);
// canvas.renderAll();
});
How do I re-render the text every time upCounter is updated?
I am trying to collect the unique json data, I mean if the key exists the update its value. But not succeed to update the value of existing key.
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},
{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},
{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"},
{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
if( coll[data.raw_id] == data.raw_id ) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
});
console.log(coll);
In fpr_data there is raw_id that i want to collect unique ids and if the raw_id found in object then update its qty and wastage with raw_qty and raw_wastage. I got Unique JSON data but quantity and wastage are not getting update. What wrong i have done? You can find the same codes in fiddle and check the result in console.
Expected: The value of qty in 3 should be 80
JSFIDDLE
Below condition will not give you correct comparison, when object already exists in array.
if( coll[data.raw_id] == data.raw_id ) {
I think you should just do:
if(coll[data.raw_id]) {
If I understand you correctly try this example
if(coll[data.raw_id]) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
You use jQuery, so enjoy the jQuery.extend() function :
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"}, {"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
console.log(fpr_data);
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
var currentObj = coll[data.raw_id]; // Try not to repeat yourself ;-)
if( currentObj == data.raw_id ) {
var q = currentObj.qty + _qty;
var w = currentObj.wastage + _wastage;
console.log(data);
coll[data.raw_id] = $.extend(data, {"qty":q, "wastage":w});
}
else {
coll[data.raw_id] = $.extend(data, {"qty":_qty, "wastage":_wastage});
}
});
console.log(coll);
I hope this is what you were looking for.
I'm trying to loop through a list of Invoices, and their Individual LineItem Values,
and in the end have an Ojbect of [object Arrays] with an Invoice Number and the total value for all line items per Invoice.
var objInvoiceLineItem = function (strInvoiceNo,strValue) {
this.InvoiceNo= strInvoiceNo;
this.Value = strValue;
}
//
var objAllInvoices = [];
//
function AddValueTo_objAllInvoices(myInvoice){
//don't know how to look and see if the Invoice exists?
//jQuery.inArray?
//for (var i = 0; i < objAllInvoices.length - 1; i++)?
if exists (myInvoice.InvoiceNo) = false{
var newObjInvoiceItem=
new objInvoiceLineItem(myInvoice.InvoiceNo, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem)
}
else{
//need help here please
var obj = getobject;
objAllInvoices.obj.Value += myInvoice.Value;
}
}
//
var Invoice1A = new objInvoiceLineItem("Invoice1",20);
var Invoice1B = new objInvoiceLineItem("Invoice1",50);
var Invoice2A = new objInvoiceLineItem("Invoice2",30);
AddValueTo_objAllInvoices(Invoice1A);
AddValueTo_objAllInvoices(Invoice1B);
AddValueTo_objAllInvoices(Invoice2A);
I think something like this will do what you want:
function AddValueTo_objAllInvoices(myInvoice)
{
for (var i = 0; i < objAllInvoices.length; i++)
{
if (objAllInvoices[i].InvoiceNo == myInvoice.InvoiceNo)
{
// invoice exists, update it and return
objAllInvoices[i].Value += myInvoice.Value;
return;
}
}
// if the invoice already existed, we would have returned in the loop
// so we wouldn't have ever gotten here, so the invoice must not exist.
// create it now:
var newObjInvoiceItem = new objInvoiceLineItem(myInvoice.Container, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem);
}