Clear localstorage values with certain prefix - javascript

I have stored several key value pairs which contains certain encrypted login information using HTML5 localstorage variables. I have added a unique prefix to all key names say TM_loginname . Now I want to clear all the localstorage key-value pairs whose key starts with prefix TM_.
PS: I tried sessionstorage too, but it clears only when browser is closed.

Removing element while iterating is unsafe, so create an array to hold the keys that need to be removed. Then, iterate over that array to remove them:
var arr = []; // Array to hold the keys
// Iterate over localStorage and insert the keys that meet the condition into arr
for (var i = 0; i < localStorage.length; i++){
if (localStorage.key(i).substring(0,3) == 'TM_') {
arr.push(localStorage.key(i));
}
}
// Iterate over arr and remove the items by key
for (var i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
}

A more modern (ES2017) solution is as follows:
Object.entries(localStorage).map(
x => x[0] # get keys
).filter(
x => x.substring(0,3)=="TM_"
).map(
x => localStorage.removeItem(x))
EDIT
Taken from the comments:
Object.keys(localStorage)
.filter(x =>
x.startsWith('TM_'))
.forEach(x =>
localStorage.removeItem(x))

Using lodash. Enjoy.
_.forIn(window.localStorage, (value: string, objKey: string) => {
if (true === _.startsWith(objKey, 'TM_')) {
window.localStorage.removeItem(objKey);
}
});

save to localStorage using
key = pref + version
function remLSPref(pref, newName) {
for (var key in localStorage) {
if (key.indexOf(pref) == 0) {
if (key != newName) {
localStorage.removeItem(key);
}
}
}
}
and use like this:
var pref = 'myid_';
var key = pref + ver;
// rem old ls
remLSPref(pref, key);

You can either:
keep an array of all the items you've created yourself or
loop over all localStorage items and filter to get the ones you
need.

Adapting the tip of github:
findLocalItems(query) {
var i,
results = [];
for (i in localStorage) {
if (localStorage.hasOwnProperty(i)) {
if (i.match(query) || (!query && typeof i === 'string')) {
var value = JSON.parse(localStorage.getItem(i));
results.push({ key: i, val: value });
}
}
}
return results; }
And after, calling the function:
var keysFounded = findLocalItems(key);
if (keysFounded && keysFounded.length > 0) {
keysFounded.forEach(k => {
localStorage.removeItem(k.key);
});
}

Related

Find an index of array item from another json array item

I am looking to find out an index and group the item belong to in a parent json group, how can I do it?
I am open to reformat the json as well if need be,
I tried JSON.stringify() but it returns the wrong index as well.
let Content = {
group1: [
[{content:"hello"},{content:"world"}],
[{content:"hello1"},{content:"world"}],
[{content:"hello2"},{content:"world"}],
[{content:"hello3"},{content:"world"}],
[{content:"hello4"},{content:"world"}],
[{content:"hello5"},{content:"world"}],
],
group2: [
[{content:"hello10"},{content:"world"}],
[{content:"hello11"},{content:"world"}],
[{content:"hello12"},{content:"world"}],
[{content:"hello13"},{content:"world"}],
[{content:"hello14"},{content:"world"}],
[{content:"hello15"},{content:"world"}],
],
};
// let currentItem = {type:'group2',index:5};
// let currentItemContent = Content[currentItem.type][currentItem.index];
let obj = [{content:"hello15"},{content:"world"}];
let newIndex = Content["group1"].indexOf(obj);
let type = "group1";
if(newIndex < 0)
{
type="group2"
console.log(Content["group2"]);
newIndex = Content["group2"].indexOf(obj);
}
console.log({"type":type,"index":newIndex});
expected: {type:'group2',index:5}
Loop through the Content object using for...in. Check if the given array is in each group by using findIndex. Since both the objects in the array seem to be in order, you can simply compare the string returned by JSON.stringify
let Content={group1:[[{content:"hello"},{content:"world"}],[{content:"hello1"},{content:"world"}],[{content:"hello2"},{content:"world"}],[{content:"hello3"},{content:"world"}],[{content:"hello4"},{content:"world"}],[{content:"hello5"},{content:"world"}]],group2:[[{content:"hello10"},{content:"world"}],[{content:"hello11"},{content:"world"}],[{content:"hello12"},{content:"world"}],[{content:"hello13"},{content:"world"}],[{content:"hello14"},{content:"world"}],[{content:"hello15"},{content:"world"}]]}
function find(input, search) {
for (const type in input) {
const group = input[type];
const index = group.findIndex(a => JSON.stringify(a) === JSON.stringify(search));
if (index != -1)
return { type, index }
}
return null
}
console.log(find(Content, [{content:"hello15"},{content:"world"}]))
console.log(find(Content, [{content:"hello"},{content:"world"}]))
You could also use Array.find in combination with Object.keys and Array.some. The array comparison you can do via JSON.stringify however remember that if your keys are in different order that would not work:
[{content:"world"},{content:"hello"}] vs [{content:"hello"},{content:"world"}]
would not match as you would expect since you are matching on strings and they are now different.
let Content = { group1: [ [{content:"hello"},{content:"world"}], [{content:"hello1"},{content:"world"}], [{content:"hello2"},{content:"world"}], [{content:"hello3"},{content:"world"}], [{content:"hello4"},{content:"world"}], [{content:"hello5"},{content:"world"}], ], group2: [ [{content:"hello10"},{content:"world"}], [{content:"hello11"},{content:"world"}], [{content:"hello12"},{content:"world"}], [{content:"hello13"},{content:"world"}], [{content:"hello14"},{content:"world"}], [{content:"hello15"},{content:"world"}], ], };
let findArray = (data, obj) => {
let index, group = Object.keys(data).find((k,i) => {
index = i
return data[k].some(x => JSON.stringify(x) === JSON.stringify(obj))
})
return { index, group }
}
console.log(findArray(Content, [{content:"hello"},{content:"world"}]))
console.log(findArray(Content, [{content:"hello10"},{content:"world"}]))

How do I check if a string matching regex already exists in array with javascript

I am trying to create array of non duplicate line going from end of array to start from another array.
I tried this:
for(var i = len; i > 0; i--){
if(resultArray[i] != undefined && resultArray[i].match(blahRegex)){
if(lastArray[blahRegex]){
console.log("entering here")
lastArray.push(resultArray[i])
}
// console.log(resultArray[i])
}
You can use filter for that.
Here is an example:
var lastArray = resultArray.filter(value => blahRegex.test(value));
Oh, just noticed that you want to keep only unique values.
var lastArray = resultArray.reduce((acc, value) => {
if(blahRegex.test(value) && acc.indexOf(value) == -1){
acc.push(value);
}
return acc;
}, []);
What this does is to retain all unique values in the resultArray array that match the blahRegex regex.
You could use a combination of filter and Set:
let lastArray = [...new Set(resultArray.filter(value => blahRegex.test(value)))];

storing key from hash in another array

I have a list of key-value pairs and I am trying to store the key N times in another array.
I'm struggling with the logic, if I iterate over the list_of_objects I can't see a way to keep track of which keys-values have already been assigned.
var kv={"a":2,"b":1,"c":1};
var list_of_objects=[bob,bill,jane,joe];//these are objects
GOAL
bob.kv="a"
bill.kv="a"
jane.kv="b"
joe.kv="c"
Notes in response to comment: kv is a property of the object bob (or bill, or jane, or joe)
You might want to try Object.keys()
Object.keys(kv).forEach(function(key) {
var val = kv[key];
while(val-- > 0) {
var obj = objects.shift();
obj.kv = key;
console.log(obj)
}
});
Similar to #MatUtter's answer but does not mutate the list_of_objects array:
var index = 0;
for (var key in kv) {
if (kv.hasOwnProperty(key)) {
var val = kv[key];
while (val-- > 0) {
list_of_objects[index].kv = key;
index++;
}
}
}

How to get a number value within an object that is in an object

My code:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var list in players.players) {
console.log(list)
var key = Object.Key(list)
console.log(Key)
}
})
What it outputs:
{ total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } }
AgentJay400
MatthewHAndreas
coolguysocoolroblox
CAMPER5155
Mavnkei
kaankerem123
egehan432
panpanaber54
IXTactical_CactusXI
Problem:
I need the number values of each user (So {AgentJay4000: 65910635} I would want the 65910635) Node.js does not seem to have Object.keys so... I have no clue how to get the number...
Node should definitely have Object.keys. If your version doesn't you should update node. When you call Object.keys you get an array in return, so you can do awesome array things like map, reduce, forEach:
Object.keys(players.players).forEach(function(key) {
console.log(key, players.players[key])
})
If you just want the number values, then map it:
Object.keys(players.players).map(function(key) {
return players.players[key]
})
Now you have an array of the numbers only.
Try like this.You can access your object value using . operator.
Suppose you have an object:
var obj={
key1:value1,
key2:value2
}
Then access values like obj.key1 or obj['key1'].
to get all the values.Use Object.values(obj);
var obj = { total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } };
var players = obj.players;
var number_values = Object.values(players);
console.log(number_values );
You can output the keys and their associated numbers by doing the following:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var key in players.players) {
console.log(key, ':', players.players[key])
}
})
To demonstrate how Object.keys works an alternative method of accessing the players - this does the same as the above.
rbx.getPlayers(539310, 1).promise.then(players => {
var keys = Object.keys(players.players);
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
let player = players.players[key];
console.log(key, ':', players.players[key])
}
});
The mistakes you made in your attempt were you were attempting to access Object.key which was a typo for Object.keys and attempting to obtain a list of keys from a string (as a loop such as for(var key in obj) will set key to each key in obj and all object keys are strings).

How to sort a JS object of objects?

I have built an object in PHP, used JSON_encode function and send it as a JSON string to my JS script via ajax. Then I convert it back to an object. The problem I am having is that I wanted to keep the object in the order that it was originally created in. Please see this picture of what the object looks like once I get it into JS:
When I created the object, it was sorted by the customer field alphabetically. The customer name starting with A would come first, B second, etc. As you can see, now, the first element of the object as customer starting with S. It looks like somehow it got automatically sorted by the key of the top-level object, which is an integer, so I understand why this happened.
So i want to do is re-sort this object so that all the sub-objects are sorted by the customer field alphabetically. Is this possible? If so, how do I do it?
Thanks!
I've changed Fabricio Matée answer to become more flexible and return the sorted object.
function alphabetical_sort_object_of_objects(data, attr) {
var arr = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var obj = {};
obj[prop] = data[prop];
obj.tempSortName = data[prop][attr].toLowerCase();
arr.push(obj);
}
}
arr.sort(function(a, b) {
var at = a.tempSortName,
bt = b.tempSortName;
return at > bt ? 1 : ( at < bt ? -1 : 0 );
});
var result = [];
for (var i=0, l=arr.length; i<l; i++) {
var obj = arr[i];
delete obj.tempSortName;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var id = prop;
}
}
var item = obj[id];
result.push(item);
}
return result;
}
Then just call the function like this
your_object = alphabetical_sort_object_of_objects(your_object, 'attribute_to_sort');
It's probably the difference between a JavaScript Object and a JavaScript Array. Objects are more like hash tables, where the keys aren't sorted in any particular order, whereas Arrays are linear collections of values.
In your back end, make sure you're encoding an array, rather than an object. Check the final encoded JSON, and if your collection of objects is surrounded by {} instead of [], it's being encoded as an object instead of an array.
You may run into a problem since it looks like you're trying to access the objects by an ID number, and that's the index you want those objects to occupy in the final array, which presents another problem, because you probably don't want an array with 40,000 entries when you're only storing a small amount of values.
If you just want to iterate through the objects, you should make sure you're encoding an array instead of an object. If you want to access the objects by specific ID, you'll probably have to sort the objects client-side (i.e. have the object from the JSON response, and then create another array and sort those objects into it, so you can have the sorted objects and still be able to access them by id).
You can find efficient sorting algorithms (or use the one below from ELCas) easily via Google.
Here's a generic iteration function which pushes all objects into an array and sorts them by their customer property in a case-insensitive manner, then iterates over the sorted array:
function iterate(data) {
var arr = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var obj = {};
obj[prop] = data[prop];
obj.tempSortName = data[prop].customer.toLowerCase();
arr.push(obj);
}
}
arr.sort(function(a, b) {
var at = a.tempSortName,
bt = b.tempSortName;
return at > bt ? 1 : ( at < bt ? -1 : 0 );
});
for (var i = 0, l = arr.length; i < l; i++) {
var obj = arr[i];
delete obj.tempSortName;
console.log(obj);
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var id = prop; //gets the obj "index" (id?)
}
}
console.log(id);
var item = obj[id];
console.log(item.customer);
//do stuff with item
}
}
Fiddle
sortObject(object){
if(typeof object === 'object'){
if(object instanceof Date){
return object;
}
if(object instanceof Array){
return object.map(element => this.sortObject(element));
} else {
return Object.keys(object).sort().reduce((result, key) => {
if(object[key] && object[key] !== null) {
result[key] = this.sortObject(object[key]);
}
return result;
}, {});
}
}
return object;
}

Categories

Resources