localStorage.removeItem() not removing key/value from object - javascript

Struggling to figure this one out...
I'm trying to remove a key/value pair, from my localStorage object. However, nothing gets removed. (I also don't have any errors).
I understand I can remove the key/value in question, by it's key name. Here's an example of the object:
bookMarksArray: [
{
"name": "reena",
"url": "brian"
},
{
"name": "joe",
"url": "ault"
}
]
And here's my code... I'm using event target to grab and match the key name, to the object index.
And then passing in key of that object index, into localStorage.removeItem()... What am I doing wrong?
list.addEventListener('click', event => {
if (event.target.classList.contains('js-delete-url')) {
const editName = event.target.parentElement.name.value;
const objIndex = bookMarksArray.findIndex(obj => obj.name === editName);
localStorage.removeItem(bookMarksArray[objIndex].name);
console.log('delete', bookMarksArray[objIndex].name);
}
});
Console prints this:
app.js:55 delete reena
Thank you!

LocalStoage saves the value in string format, so you have to stringify JSON object every time to save it in localStorage, we can solve this problem, please find below code snippet, useful in this scenario,
var updateStorage = function(filterName) {
var bookMarksArray= [{"name": "reena", "url": "brian"}, {"name": "joe", "url": "ault"}]
localStorage.setItem('nameList', JSON.stringify(bookMarksArray));
var items = JSON.parse(localStorage.getItem('nameList'));
var updatedList = items.filter(function(a) {
return a.name !== filterName;
});
localStorage.setItem('nameList', JSON.stringify(updatedList));
console.log(localStorage.getItem('nameList'));
// result [{"name":"reena","url":"brian"}]
};
updateStorage('joe');

//set js object to localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))
//get js object from localstorage
bookMarksArray= JSON.parse(localStorage.getItem('bookMarksArray'))
//remove desired item
bookMarksArray = bookMarksArray.filter(function(item) {
return item.name !== 'reena';
});
//update js object in localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))

Related

JavaScript array of huge data (500K record) taking time to search and add

My function is called in loop which returns more than 500k record.
I have to insert that record in a JavaScript array. Before inserting records to array need to check existing array has duplicate records or not. If the record is duplicate then exclude the record.
When array size increases the run time of the function is very high. Please suggest me a way to optimize search.
function AddDataToArray(StdName, currObjectSTD, bufferObject, attributes, bufferSTD) {
var result = false;
var existingObjects = AllDataArray.find(item => {
item.OBJECTID==attributes.OBJECTID
&& item.name == bufferObject.name
&& item.StdName == StdName);
});
if (existingObjects.length == 0) {
var currentObject = {
"ID": 0,
"currObjectSTD": currObjectSTD,
"color": bufferObject.color,
"name": bufferObject.name,
"attributes": attributes,
"StdName": StdName,
"objectID": objectID,
"bufferSTD": bufferSTD,
"shape": null,
"shapeSTD": null
};
AllDataArray.push(currentObject);
result = true;
}
return result;
}
As a speedup workaround I suggest you coming up with some kind of hash map based on your array to avoid continuos looping through array
const dataHashMap = _(AllDataArray)
.keyBy(item => `${item.OBJECTID}-${item.name}-${item.StdName}`)
.mapValues(() => true)
.value();
var existingObjects = dataHashMap[`${attributes.OBJECTID}-${bufferObject.name}-${StdName}`]
or alternative solution
let groupedDataHashMap = {}
AllDataArray.forEach(item => {
_.set(
groupedDataHashMap,
[
item.OBJECTID,
item.name,
item.StdName
],
true
)
})
var existingObjects = _.get(
groupedDataHashMap,
[
attributes.OBJECTID,
bufferObject.name,
StdName
],
false
)
I used lodash methods but if you prefer using native array/object methods you can come up with your own implementation, but the idea is the same
P.S you need to create this hash map once you fetched your array and populate it with new items simultaneously with your array to keep it up-to-date with your array

How to access variables inside an array

So, I have been trying to solve this all of yesterday and today but cannot figure it out. I have the following returned in a variable called
var myRequest = req.body
console.log(myRequest)
Produces the following:
{
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
}
Now, I need to access the params key, and access the first param value so that whatever is returned in the first param value string is stored as username in a variable, and whatever is returned in param value string (the second one), is stored as a password.
So the final effect something like this:
var username = myRequest.methodcall.params.param...first value string
var password = myRequest.methodcall.params.param...second value string
However, I am really struggling to understand how to do this. Im guessing forEach loops would come in this, however I do not have experience with them so would appreciate some tips.
Also, when I try doing myRequest.methodcall, I keep getting undefined returned.
Any help will be greatly appreciated!
It sounds like your value is in JSON, parse it first and then you should presumably be able to get its values:
var myRequest = JSON.parse(req.body);
var userName = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
What you have posted is JSON. you need to set it up like:
var myRequest = JSON.parse(req.body)
this will allow you to access the it like a normal js object.
Use . to access keys in object and [] to access index in array.
This code should work:
var username = myRequest.methodcall.params[0].param[0].value[0].string[0]
If you would like to use a loop at get the values test1,password, and so on. You can use a loop and access the param array:
var params = myRequest.methodcall.params[0].param;
params.forEach(function(item){
console.log(item.value[0].string[0]);
});
Fiddle
//var myRequest = JSON.parse(req.body) // if JSON
var myRequest = {
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
};
var params = myRequest.methodcall.params;
var uname, pwd;
for (var i = 0; i < params.length; i++) {
console.log("uname is " + params[i].param[0].value[0].string);
console.log("pwd is " + params[i].param[1].value[0].string)
}
if your response structure will be same then no need to go for loop or something, just directly access the username and password from response.
try this.
var username = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
Did you debug your code?
I mean these code:
var username = myRequest.methodcall.params.param[0];
var password = myRequest.methodcall.params.param[1];

How to delete a key within an object in local storage with Javascript and/or Jquery?

In local storage I have an object named favourites and it contains this..
"{
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
}"
How can I delete an object based on its ID (id3333 & id4444 for examples)
I have tried the following along with some other voodoo..
localStorage.removeItem('id3333'); // no errors, no removal
localStorage.removeItem('favourites':'id3333'); // SyntaxError: missing ) after argument list
localStorage.removeItem('favourites[id3333]'); // no errors, no removal
localStorage.removeItem('id3333', JSON.stringify('id3333')); // no errors, no removal
Also, I will need to get the key name to delete based on a variable, so like this..
var postID = 'id3333';
localStorage.removeItem(postID);
or
var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);
Is it possible to remove a nested item directly or do I need to retrieve the full object and then delete the item and then set the object back to local storage again?
The closest I can get to deleting anything directly so far is..
localStorage.removeItem('favourites');
But that of course removes the entire object.
You have a a single key and you are acting like there are multiple keys
var obj = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
window.localStorage.favs = JSON.stringify(obj); //store object to local storage
console.log("before : ", window.localStorage.favs); //display it
var favs = JSON.parse(window.localStorage.favs || {}); //read and convert to object
var delKey = "id3333"; //key to remove
if (favs[delKey]) { //check if key exists
delete favs[delKey]; //remove the key from object
}
window.localStorage.favs = JSON.stringify(favs); //save it back
console.log("after : ", window.localStorage.favs); //display object with item removed
With localStorage.removeItem you can only remove top level keys, i.e. keys directly on localStorage.
Because id3333 is on localStorage.favourites you cannot remove it using localStorage.removeItem.
Instead try delete localStorage.favourties['id3333']
Simple, actually: you just delete it. :)
x = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
console.log(x);
delete x.id3333;
console.log(x);
delete does what you're looking for. You could also do something like delete x.id3333.TITLE if you were so inclined. Note also that delete returns true if successful and false if not.
Suppose you set a nested object in localStorage like that
const dataObj = {
uid: {
name: 'robin',
age: 24,
}
}
window.localStorage.setItem('users', JSON.stringify(dataObj));
Now you want to delete the age property. You can't remove it with removeItem native function since it allows to delete from top level.
So you need to get the data first and delete the property you want and set the data again to localStorage with updated value like that
const existingLocalStorage = JSON.parse(window.localStorage.getItem('users') || {});
if(existingLocalStorage['uid']['age']) { // if throws any error, use lodash get fucntion for getting value
delete existingLocalStorage['uid']['age'];
}
window.localStorage.setItem('users', JSON.stringify(existingLocalStorage));

Selecting a JSON object by number not by name

I try to store a JSON object with informations in multiple languages. Im not even sure they way i did it is good, any suggestions are welcome.
My current problem ist, that i dont know how to access the first language without knowing what language it is.
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
document.write(Data[1].Name);
I just want to access the second object, sometimes its "en", sometimes its "de".
Thanks for any tipps!
Here is a pure javascript solution:
First: You get the keys of the object:
var keys = Object.keys(Data);
Then: The keys are stored in a array. You can access them with an index. Like:
Data[keys[0]]
Now: You can use a foor loop or whatever you want :)
Data is an object its not array so you cant access it like Data[0] you can access it like Data.en.
but as you say you dont know any thing about en or de so i suggest that you form the Data object like this :
var Data =[{
lang:"en",
langData:{
Name:"Some name"
}
}]
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
var index = 0;
$.each(Data, function(key, val){
index += 1;
if (index == 2){
// key is the language, like in this example key is 'en'
console.log(key);
}
});
var name = (Data.en || Data.de || {})['Name'];
(Data.en || Data.de || {}) get's value of Data.en or Data.de if both doesn't exist, return empty object, so that script doesn't throw exception for Name property
()['Name'] same as myObject['Name'], myObject.Name
assign value to name variable, it will be Some name or undefined at least
If you have more languages, add them all, notice: it will return first found lang
var name = (Data.en || Data.de || Data.ru || Data.fr || {})['Name'];
Use Object.keys method to get list of object property names:
console.log(Data[Object.keys(Data)[1]]['Name']); // "Some name"

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

Categories

Resources