Remove json object in localstorage using js - javascript

[{'id':1,'content':'something'},{'id':2,'content':'something diff'},{'id':3,'content':'something diff'}]
by localStorage.getItem('data') I got the above json object, but how to delete the id 2 item?

Assuming you've JSON.parse'd your local storage data into an array, you can remove the second item like you would from any other array- by popping it off.
var data = localStorage.getItem('data');
// At this point, data is either null or a string value.
// To restore the string to an Array you need to use JSON.parse
if (data) {
data = JSON.parse(data);
// At this point you can use Array methods like pop or splice to remove objects.
}
// At this point, your Array will only contain the first item.
// If you want to write it back to local storage, you can like so:
// Be sure to use JSON.stringify so it can later be restored with parse.
localStorage.setItem('data', JSON.stringify(data));

This will turn "data" into a javascript object and remove the last item (assuming this is always an array):
var data = localStorage.getItem('data');
if (data) {
data = JSON.parse(data);
data.pop();
}

Related

Why does my push function store my data in a nested manner?

I am working on updating my localStorage to store specific data after every transaction made by the client user. I noticed that my code saves the data in a nested format. This is not desirable.
What would be desirable is if the data is stored in un-nested format.
Find attached descriptive images, to give you a clearer idea of what I mean.
How do I formulate my code to save these data in NON nested manner?
Find below my code
var newData = {}; var transactionDataRetrieved = [];
newData.TransactionTime= "Thu 20:11",
newData.amount= "15,000",
newData.payersNumber= "070505788",
newData.transactionNumber= "PSC999",
newData.waitersName= "Agnes Johnsson!"
transactionDataRetrieved.push({newData: newData});
transactionDataRetrieved.push(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
The problem is that you are pushing the old value onto a new array every time and then saving it back. Here's one (untested) alternative, adding the newest data to the end. It wouldn't be hard to modify it to put that data at the beginning.
var transactionDataRetrieved = JSON.parse(localStorage.getItem('transactionData') || '[]');
var newData = {};
newData.TransactionTime = "Thu 20:11",
// ...
transactionDataRetrieved.push(newData);
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
Or in a single expression:
localStorage .setItem ('transactionData', JSON .stringify (
(JSON.parse (localStorage .getItem ('transactionData') || '[]') .concat (newData)
))
You are pushing array to array
// pushing object to array
transactionDataRetrieved.push({newData: newData});
// pushing array to array
// localStorage.getItem('transactionData') returns array
// because you created, var transactionDataRetrieved = []; as array
transactionDataRetrieved.push(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(transactionDataRetrieved));
What you should be doing
transactionDataRetrieved.push({newData: newData});
// changed push to concat
var newArray = transactionDataRetrieved.concat(JSON.parse(localStorage.getItem('transactionData')));
localStorage.setItem('transactionData', JSON.stringify(newArray));
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
There are some minor issues with your code that I want edit check it:
var newData = {};
newData.TransactionTime= "Thu 20:11",
newData.amount= "15,000",
newData.payersNumber= "070505788",
newData.transactionNumber= "PSC999",
newData.waitersName= "Agnes Johnsson!"
// **newData** is already an Object so don't wrap it in an object
//First get data from the localStorage;
//store it in array of Objects
var transactionDataRetrieved = localStorage.getItem('transactionData');
transactionDataRetrieved.push(newData);
//Now set this array in local storage
localStorage.setItem('transactionData', transactionDataRetrieved);

Using localStorage/sessionStorage to store arrays

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.
// setting values
localStorage.setItem("foo", [15,"bye"]);
// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye
// only writes the first character, instead of one part of the array
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1
I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.
Try this:
localStorage.setItem("foo", JSON.stringify([15,"bye"]));
// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye
var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
localStorage can only store string in its value, that is why it is storing only 15;
Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]));
If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));
You can parse json
let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
Or you can split by ',' and get the 0th index item.
localStorage.getItem('foo').split(',')[0]

chrome.storage.local.get an object and iterating through obj keys

I'm having trouble using the chrome.storage.local.get feature. I have all working, except I don't understand how to handle the .get function.
I want to copy an object by clicking a button, from one chrome tab to another one. I have a loop to get my Object keys, and I can save it successfuly in chrome local storage by:
chrome.storage.local.set({
'copiedObj': obj
});
but, when trying to use the .get function, I can't specify the key number I want. I need the key number because the keys and their values changes every time because i'm copying data from different pages.
$('#targetInfo').click(function(){
console.log('context 2 received');
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
});
this gets me the full object keys and values, but when trying to change it to get the first key (changing the console.log inside the script to items[0], I get an undefined error message in the console.
I want it to iterate through all the keys, and assign key to a variable, value to a variable and execute a function. For each key by it's time. I've written a detailed explanation inside the code:
//Get the DOM input field
var specific_name = document.getElementById('new_specific_name');
var specific_value = document.getElementById('new_specific_value');
//Start loop, from 0 to the last object keys
for (i=0;i<items.length;i++) {
//Set specific_name value to the first key inside the object
specific_name.value = XXX[i];
//Set specific_value value to the matching key value inside the object
specific_value.value = ZZZ[i];
//Execute this function
add_new_specific();
}
(minimal solution, pending clarification) As mentioned before,
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
should be
var storage = chrome.storage.local.get('copiedObj', function (result) {
console.log(result.items);
console.log(result.items[0]); // if items is an array...
});
To loop through an object, see https://stackoverflow.com/a/18202926/1587329. You need to do this all inside the anonymous function in .get.

Javascript logic to push value to array once and update the value afterwards

Could anyone suggest me a logic where i have to push data to an array once, and there after i should be updating the pushed data. If i use array.push then it appends the data each time but i just want to push data once and update it afterwards.
I'm not entirely sure what you're asking but if you're trying to add an object to an array and update it without further appending to the array...
var a = [];
var data = {};
// add `data` to array `a`.
a.push(data);
// Update property `property` of `data` to value.
// This also updates `a[0]`.
data.property = 'value';
a[0].property2 = 'othervalue';
a[0].property == 'value'; // true
data.property2 == 'othervalue'; // also true
In short, data and a[0] refer to the same object in memory and an update to one will update the other.
Your can check if there is a value exist in array then pop data from array and push data every time in array
If(arr.length >= 1)
{
arr.pop();
}
arr.push(data);
OR
arr[0] = data;
That will also work
Thanks

jQuery .getJSON return into array variable & json array manipulation

is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.
Something like:
$.getJSON('itemManager.php?a=getItems', function(data){
// itemArray = new Array(data);
// idsArray = new Array(data.id);
for (var i in someOtherArray){
if($.inArray(i, idsArray) == -1){
// do something...
// get jason variable by id?
// itemArray[i].someVariable
}
}
}
EDIT: JSON structure
[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]
This is basically the idea.
Get all the values
Isolate the id values of JSON objects
Loop another array
Check if json id is inside the other array
Access other json variables by id value
There are various solutions here I guess, but I'm looking for something with minimal code.
With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:
$.getJSON('itemManager.php?a=getItems', function(data){
var items = {};
for(var i = data.length; i--; ) {
items[data[i].id] = data[i];
}
for (var j = someOtherArray.length; j--; ){
var item = items[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
It woud be even better if you create this structure on the server already, then it would be:
$.getJSON('itemManager.php?a=getItems', function(data){
for (var j = someOtherArray.length; j--; ){
var item = data[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.
Update:
To create the appropriate structure on the server with PHP, you have to create an associate array.
So at the point where you add an object to the array, you should not do
$items[] = $obj;
but
$items[$obj->id] = $obj; // or $obj['id'] if you have an array
If you get an array as your JSON response then your data variable in your callback is an array, no need to do anything with it.
If you get an object as your JSON response as the data.id in you example might suggest, and some of it's values is an array, then just use data.id as an array, or use var array = data.id; if that is more convenient for you.
Remember that data in your callback is just whatever you got as JSON. It can be an object (which is an associative array), an array, a string, a number, or a true, false or null value. If it is an object you access it using data.key, if it is an array you access it using data[index]. I say it because I suspect that you might be confusing arrays with objects here.

Categories

Resources