Update Value in Localstorage Array by Existing Key

update value in localStorage array by existing key

Solution :

function addToCart(id, qty) {
var newItem = true;
var basket = json.parse(localStorage.getItem('basket'));
basket.forEach(function (item){
if(item.product_id == id) {
item.quantity += qty;
newItem = false;
}
})
if(newItem) {
basket.push({
product_id: id,
quantity: qty
});
localStorage.setItem('basket', JSON.stringify(basket));
}
}

How do you update an array in localStorage without overwriting same-key values?

I've cleaned up the code a little.

Your code should work, except that is was missing some error handling for the first load.

// Mock data
const name = { value: 'Foo name' };
const about = { value: 'Bar about' };
const submitbtn = document.getElementById('submit');

// Fake localStorage to make it work in the snippet
mockLocalStorage = {
getItem: (key) => this[key],
setItem: (key, value) => this[key] = value
};

submitbtn.addEventListener('click', function() {
// Make sure we get -something- back in case this is the first time we're accessing the storage.
const oldInfo = JSON.parse(mockLocalStorage.getItem('data') || '[]');
console.log('Before', oldInfo);

// The creation of the new object can be done in 1 step.
const array = Object.entries({
name: name.value,
about: about.value
});

oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log('After', oldInfo);
mockLocalStorage.setItem('data', JSON.stringify(oldInfo));
});
<button id="submit" type="button">Submit!</button>

How do I update specific key value of the local storage array?

You can use following;

var pageItems  = '{"stationID":"145","categoryID":"-1","pickupDate":"2014-04-22","pickupTime":"08:00","returnDate":"2014-04-23","returnTime":"08:00","milage":"false","miles":"","attributes":[[],[]],"additionals":[[],[]]}';

var json = JSON.parse(pageItems);

json.categoryID = 65;

pageItems_v2 = JSON.stringify(json);

Here is a working demo : Demo

How to update localstorage object value from index and key

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));

}

Update specific value of object in localStorage

This can help:

let responseJson = {
id: user.id,
username: user.username,
firstName: user.firstName,
dataId: 1000
};

let loggedInUser = JSON.parse(localStorage.getItem('user_id'));
loggedInUser.dataId = parseInt(2000);
localStorage.setItem('user_id', JSON.stringify(loggedInUser));

enter image description here

how to update array obj in localStorage if item is already exist

You can't avoid stringifying localStorage data.

var data = JSON.parse( localStorage.getItem('cart') );
for (var key in drinkCounter) {
...

// search for a product with current key
var index = -1;
data.forEach(function(item, i){
if( item.Product === key ) {
index = i;
}
});

if (index !== -1) {
// data[index] = cartObj;
data[index].Quantity = parseInt(data[index].Quantity.split(x)[0]) + drinkCounter[key].count + 'x ';
} else {
var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' };
data.push(cartObj);
}
...
}

localStorage.setItem('cart', JSON.stringify(data));

Updating localstorage arrays in Javascript

This seems to be the problem with passing the key of local storage without quotes.

While reading from local storage use the key as argument as it stores the value as key/value pairs.

yesArray = JSON.parse(localStorage.getItem("yesArray"));


Related Topics



Leave a reply



Submit