How to update localstorage object value from index and key - javascript

I need this solution for my project. its very important for me.
i want to update object value with key and index, from local storage
FOR
my cart application.
(Decrease button for product quantity in cart)
Exmp.
function decreaseQuantity(index) {
var oldQty = localStorage.cart[index].quantity;
var newQty = oldQty - 1;
localStorage.setItem(cart[index].quantity, newQty);
}

You can't store complex object in localStorage, you can store data as string only.
If you want to store the cart object to locaStorage , you need to serialize it as string using JSON.stringify and store it like following.
window.localStorage.setItem('cart', JSON.stringify(cart));
Note: here 'cart' is the key.
To get back, change it and store back, you need to do like following.
var data = window.localStorage.getItem('cart');
if (data != null) {
let cart= JSON.parse(data);
cart[index].quantity = cart[index].quantity -1;
window.localStorage.setItem('cart', JSON.stringify(cart));
}

its worked for me #PSK thanks for your efforts
#adiga I guess I made a logic error. thank you too, for your interest !

Related

Parsing strings from local storage with vanilla JavaScript [duplicate]

This is my code. I am trying since a couple of days to create an Array of Objects, which I will then store in Local Storage. Here is the problem, I need to first Get the existing value from Local Storage.
I then need to add the new data object to the existing array. I then convert it into JSON so that I can store it back in the local storage.
onRegisterSubmit(){
const user = {
a: this.a,
b: this.b,
c: this.c,
id: Date.now()
}
var abc = [];
var get = JSON.parse(localStorage.getItem('user'));
abc = [get];
abc.push(user);
localStorage.setItem('user', JSON.stringify(abc));
console.log(JSON.stringify(abc));
console.log(get);
}
I want the JSON to be an array of objects like this,
[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}]
This is my JSON.
[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]
I've been trying for several days and any help will be greatly appreciated.
The issues with that code are:
You're wrapping the result you get in an array, but in theory, you want to already have an array.
You're storing user, not get or abc. (You removed that with an edit.)
To store the array, do what you're doing:
localStorage.setItem("users", JSON.stringify(users));
To get the array:
users = JSON.parse(localStorage.getItem("users") || "[]");
Note how that provides a default (empty array) if getItem returns null because we've never stored our users there.
To add a user to the array:
users.push({id: 1, foo: "bar"});
Example (live on jsFiddle [Stack Snippets don't allow local storage]):
(function() { // Scoping function to avoid creating globals
// Loading
var users = JSON.parse(localStorage.getItem("users") || "[]");
console.log("# of users: " + users.length);
users.forEach(function(user, index) {
console.log("[" + index + "]: " + user.id);
});
// Modifying
var user = {
id: Math.floor(Math.random() * 1000000)
};
users.push(user);
console.log("Added user #" + user.id);
// Saving
localStorage.setItem("users", JSON.stringify(users));
})();
That shows you the list of current users in the console, adding one each time you refresh the page.
Try something like this:-
link https://jsfiddle.net/sureshraina/nLexkyfw/1/
var mydatas = new Array();
mydatas[0] = "data";
mydatas[1] = "data1";
mydatas[2] = "data2";
localStorage["mydatas"] = JSON.stringify(mydatas);
var datas = JSON.parse(localStorage["mydatas"]);
See this post.
You can't store Objects, you have to store a String. So the workaround is to stringify your Object before you store it (for example, you could use change it to a JSON object, store it, and read it again when needed).

How to amend a new key to existing object using session storage

I have below piece of code
addToFilterCriteriaTree(componentData) {
let id = componentData.props.data.id;
this.state.filterCriteriaTree[id] = componentData.criteria;
}
Instead of state ,I want to create a object 'filterCriteriaTree' using setStorage and add a new key to it
I've changed the parameters since it's cleaner to supply only the data needed for the function to do it's job rather than the entire object.
addToFilterCriteriaTree(id, criteria) {
let currentFilterCriteriaTree = JSON.parse(sessionStorage.getItem('filterCriteriaTree')) || {};
currentFilterCriteriaTree[id] = criteria;
sessionStorage.setItem('filterCriteriaTree', JSON.stringify(currentFilterCriteriaTree);
}

Pulling last value in json file

I have a json file and I need to pull the last value from a particular customer id. The Json file is updated throughout the day and I have this setup to just be a function that will pull the last job number within the customer ID.
Json
[{"CustId":"5886708366","JobNumber":"636275400282798443c"},{"CustId":"123456798","JobNumber":"636275400535607074c"},{"CustId":"5886708366","JobNumber":"636275413000246135c"},{"CustId":"5886708366","JobNumber":"636275415626921919c"},{"CustId":"5926680270","JobNumber":"636275435491908861c"},{"CustId":"5926680270","JobNumber":"636275436824699429c"},{"CustId":"5926680270","JobNumber":"636275440818384096c"}]
I only need to pull from customer ID 5886708366 and use the last jobnumber in this case 636275415626921919c.
I have so far I have the following.
var picarioAPI = "where I pull the json file";
$.getJSON(picarioAPI, function (json) {
for (i in json)
if (json[i].CustId == {{ customer.id }}) {
I'm stuck on getting the last part. I'm able to loop through the jobs but cant just call just that last one. Any help would be great.
The way to fetch last of the requested CustId within your array is as follows;
var json = JSON.parse('[{"CustId":"5886708366","JobNumber":"636275400282798443c"},{"CustId":"123456798","JobNumber":"636275400535607074c"},{"CustId":"5886708366","JobNumber":"636275413000246135c"},{"CustId":"5886708366","JobNumber":"636275415626921919c"},{"CustId":"5926680270","JobNumber":"636275435491908861c"},{"CustId":"5926680270","JobNumber":"636275436824699429c"},{"CustId":"5926680270","JobNumber":"636275440818384096c"}]');
var lastObj = json.reverse().find(obj => obj.CustId == "5926680270");
console.log(lastObj.JobNumber);
Reverse the JSON array, find the object with your customerId, and fetch its jobNumber, very straightforward one-liner.
If you know for sure that you will only need the last item you could get it like this:
var lastItem = json[json.length - 1];
If you know the customer ID before hand you could use the find method, which would better if the customer might not always be at the last position of the array
var customer = json.find(val => val.CustId === '5926680270')
Try looping through your array in reverse to get the most recent.
for (var i = length - 1; i > 0; i--) {
if (json[i].CustId == {{ customer.id }}) {
}
}

Prevent a duplicate item being added in Localstorage with AngularJS

I am working on a prototype that stores products (like a favourite) into localStorage but I am struggling to check to see if an item already exists in localStorage so its not added again.
Where would the best place be to check for a duplicate entry and handle it gracefully?
My sample controller is below:
function dCtrl($scope, $filter) {
$scope.d = [
{id:'1',d_name:'Product 1',colour:'Blue'},
{id:'2',d_name:'Product 2',colour:'Red'},
{id:'3',d_name:'Product 3',colour:'Cream'},
{id:'4',d_name:'Product 4',colour:'White'},
{id:'5',d_name:'Product 5',colour:'Green'},
{id:'6',d_name:'Product 6',colour:'Black'},
{id:'7',d_name:'Product 7',colour:'Purple'},
{id:'8',d_name:'Product 8',colour:'Grey'},
{id:'9',d_name:'Product 9',colour:'Yellow'},
{id:'10',d_name:'Product 10',colour:'Indigo'}
];
$scope.getDetails = function (id, favDresses) {
//get the object of the item clicked
single_object = $filter('filter')($scope.d, {id:id})[0];
// If you want to see the result, check console.log
console.log(single_object);
console.log('ID:' + id + ' - save this object to localStorage');
//set localstorage var
var storage = localStorage.getItem('newfavdresses');
//check to see if the localStorage array is empty (not null)
if(storage != null) {
//if it isnt, parse the string
favDresses = JSON.parse(localStorage.getItem('newfavdresses'));
//push into the array
favDresses.push(single_object);
//set the item in localstorage
localStorage.setItem("newfavdresses",JSON.stringify(favDresses));
} else {
//if the array is null, create it
var favDresses = [];
//and push the item into it
favDresses.push(single_object);
//set the item in local storage
localStorage.setItem("newfavdresses",JSON.stringify(favDresses));
}
}
$scope.clearStorage = function() {
localStorage.clear();
alert('Local Storage Cleared');
}
//get localStorage items
var dresses = localStorage.getItem("newfavdresses");
dresses = JSON.parse(dresses);
console.log(dresses);
}
jsFiddle demo - https://jsfiddle.net/dwhiteside86/Lt7aP/2261/
My suggestion is work with live javascript array stored in service.
You would load this array from localStorage when service initializes or set to empty array if nothing in storage.
Then whenever you update the stored array you always store back the whole thing into localStorage so that the stored version is always a string replica of the live one.
This way you only use getItem() once and then have a simple service method storeLocal() that you call each time you modify array or object in array.
Another thing you might look at is ngStorage that does all of the above for you
Look at https://github.com/grevory/angular-local-storage, I believe it will solve all your issues. This library will bind your scope property to local storage so You'll dont care about how it stores.

Javascript matrix array issue

I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}

Categories