Get ID by key in localStorage - javascript

In JS localStorage I can use
localStorage.getItem(key);
to get the value of the entry corresponding to the key in the key variable.
How can I get the entry's ID (instead of value) using the key?
Edit: sorry I must have confused people. What I mean by "key" is the numerical key - which is 0, 1, 2, 3 etc depending on how many items have been saved. Then I want to find out the ID it was stored as, eg foo in the below example, from the numerical key.
localStorage.setItem('foo', 'bar');

LocalStorage is implemented as a key-value pair ( see for instance: https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage ) - so you don't have an id like an unique auto-incremented id in a database table.
However, you can access the elements using an index - to get the index of a key in localStorage, the only way I can find is to loop through each key until you find the one you are searching for, like this:
var findIndexOfKey = function(searchKey) {
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if(key === searchKey)
return i;
}
return -1;
}
And then, to retrieve the key using the index, you can do:
localStorage.key(myIndex);
And to retrieve the value, you can do this:
localStorage.getItem(localStorage.key(myIndex));
... or this ( which would be equivalent to localStorage.getItem("myKey")):
localStorage.getItem(localStorage.key(findIndexOfKey("myKey")));

when setting the item you should give it's ID as a value and than when you call getItem(key) it should give it's ID as a return ex:
localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // it should return the bar
take a look for this examples it may help : http://mathiasbynens.be/notes/localstorage-pattern

The answer:
localStorage.key(key);
Sorry, I realise I've got confused between what's actually called the key, which I called the ID, and it's numerical ID which I called the key...

I don't think it is possible. Can't you just make localStorage.setItem(yourkey,value)? I mean
localStorage.setItem(0,value)
localStorage.setItem(1,value)
This may be useful in loops for example.

Related

Possible to .push() to a dynamically named key?

I have an object that I would like to push an indeterminate amount of other objects to, using a loop. To keep it organized, I'd like to dynamically name the keys based on them amount of times the loop runs. I have the following:
let formsJson = {};
let counter = 1;
//savedForms are where the objects that I want to push reside
savedForms.forEach( form => {
formsJson['form'+counter] = JSON.parse(form.firstDataBit_json);
//This is where I'm having trouble
counter = counter + 1;
});
I can push the first bit of data fine, and name the key dynamically as well. But I need to push 2 more objects to this same dynamic key, and that's where I'm having trouble. If I try the obvious and do:
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
I don't get any output. Is there a way to accomplish this?
forEach() gives you access to the index already. No need to create the counter variable. Example usage. I would definitely recommend using a simple index, and not using the 'form'+counter key.
In your example, it's not clear to me that the value being assigned in the forEach loop is an array. So it's unclear if you can push to any given element in that. But generally that syntax should
Personally, I would prefer to have a function that outputs the entire value of the element. That would provide better encapsulation, testability, and help enforce default values. Something like:
function createItem(param1) {
let item = [];
item.push(param1.someElement);
if (foo) {
item.push(...);
} else {
item.push(...);
}
return item;
}
formsJson['form'+counter] = createItem( JSON.parse(form) )
So you're making formsJson['form'+counter] a by assigning the JSON parse, not an array as you want. Try this:
formsJson['form'+counter] = [];
formsJson['form'+counter].push(JSON.parse(form.firstDataBit_json));
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
Maybe you want to figure out something like this
savedforms.forEach((form, index) =>
formsJson[`form${index + 1}`] = [ JSON.parse(form.secondDataBit_JSON)])
Now you can push on the item
formsJson[`form${index + 1}`].push(JSON.parse(form.secondDataBit_JSON));`
Also here you'll save operation on incrementing it will be automaticly

Finding a particular value in a Javascript object

I humbly ask for assistance. I am working on a project where I need to set up a search to find all instances, inside an Object where a particular value equals whatever term the user is searching for. I found the following code:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
here (to make sure proper credit is given),which works great, but I am looking for some help on expanding the functionality of this code to include the ability to search for more than one element at a time, and also, on the return, display other values in the same objects being returned. As an example, the returns, using the above code, are simply [Object]:
What I was hoping to do was to append the [>Object] with another variable value from the Object, perhaps the ID or Description, both of which are part of the returned results. So, the desired results would be something like "Object: ID=b01" or "Object: Desc = This is Maple", something that will allow my users to quickly see which one of the results they need to look at.
Thank you in advance for your assistance!
From your description, I have changed the function to look through a tree like object and be able to pick out the objects that contain all of the supplied key-value pairs. In addition, it allows you to specify that you want to output extra parameters on the objects that match. (like the id and description)
Here is the code and example
http://jsfiddle.net/hjhQz/

Store function result to variable

How can I store the result of a function to a variable?
In navigating an object that contains an array, I am looking for one value, value1, once that is found I want to get the value of one of its properties, property1.
The code I am using below is an example and is incorrect.
function loadSets(id){
clworks.containers.find(function(i){
return i.get('property1')===id;
});
}
My intent is to navigate the object below:
clworks.containers
containers[0].property0.id
containers[1].property1.id
I am trying to determine how to find which item in the array has a property value equal to the id used in the function and then store it as a variable.
Simply:
var myVar = loadSets(id);
EDIT
Ok, as much as I understand your question now, your situation is the following:
You have an array containing objects called containers;
You want to iterate through this array, looking for the property id of the property property1 which equals the one specified in the function called loadSets(id);
Once found, store the object with the requested id in a variable.
Am I right?
If so, this should solve your problem:
// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {
for(i=0; i < containers.length; i++) {
if( containers[i].property1.id === id )
return containers[i];
}
return false;
}
After this you just need to do what I said in the first answer to your question, triggering it however you want. I put up a quick JSBin for you. Try to put 10, or 20, in the input field and then hitting the find button; it will return the object you are looking for. Try putting any other number, it will return a Not found.
Currently your function, loadSets, isn't actually returning anything and so you cannot store a result from it.
Try:
function loadSets(id){
return Base.containers.find(function(i){
return i.get('entityid')===id;
});
}
And to get a result into a variable:
var result = loadSets(id);

json jquery filter javascript array

I have a json object array. I want to search the array and for each object, create a list of 'services' that is a comma-seperated list of all the keys which have a value of "yes".
The list of json objects with the services list is then displayed in html using jquery's each.
Its a large json file so I want to do it as efficiently as possible.
I already have the object's properties being accessed through jQuery's each (ie, obj.name)
-- so I think it should be possible to filter the services listed for each object using
jQuery's filter, and then display the key if the value is yes.
But it seems like a more efficient option would probably be to create a new javascript array, join the services with a value of yes and then add that variable to the html being
appended.
Im not sure which would be faster and so far havent been very successful at either... so any advice and examples would be very helpful.
Here's what the json array looks like:
[
{"name":"name1",
"service1":"y",
"service2":"y",
"service3":"n",
},
{"name":"name2",
"service1":"n",
"service2":"y",
"service3":"n",
},
];
If you just want to filter the array then use grep.
grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
http://api.jquery.com/jQuery.grep/
First off, delete trailing commas. Internet Explorer gets really, really confused by them. Anyway, I assume you don't want to "search" the array when you say "for each value"; you want to iterate through the array and parse it into a more usable list. The first method I'd suggest is just passing what you want as the array you desire, but if that's not an option, what you're looking for is some variant of this, which should be fairly efficient (jsFiddle example):
var json = [
{"name":"name1", "service1":"y", "service2":"y", "service3":"n"},
{"name":"name2", "service1":"n", "service2":"y", "service3":"n"}
];
var parsed = {};
for (var i = 0, iLen = json.length; i < iLen; i++) {
// Assuming all we need are the name and a list
var name;
var list = [];
for (var key in json[i]) {
var value = json[i][key];
// We need to hold on to the name or any services with value "y"
if (key === "name") {
name = value;
} else if (value === "y") {
list.push(key);
}
}
// Add them to the parsed array however you'd like
// I'm assuming you want to just list them in plain text
parsed[name] = list.join(", ");
}
// List them on the web page
for (var key in parsed) {
document.write(key + ": " + parsed[key] + "<br>");
}
That way you wind up with a display to the visitor of the services available and still keep an array around for further use if necessary.
jQuery.inArray() Search for a specified value within an array and return its index (or -1 if not found).
http://api.jquery.com/jQuery.inArray/
Or
http://api.jquery.com/jQuery.each/

How to set certain element values to null in JavaSctipt

I have some items I am storing in an element that get added at various times like this:
document.getElementById('rout_markers').value = str;
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
How can I do that?
Thanks!
If you're assigning str to an element then there are no arrays involved here - you'll be overwriting each previously-assigned value with the latest and thereby storing only the latest value.
You could use an array but you'd have to know the location of each item in the array, so if you wanted to assign or nullify a specific element in your array, you'd have to a have a record of where it was - although you could get around that it with a multi-dimensioned array, where the first element at each index is the name of the property, and the second element at each index is that value of the property.
If you want to store multiple properties in a field in order to retrieve them all later, there are two simple ways of doing this.
Consider using either a field for every property.
If you do this then I'd suggest using a naming convention for the fields so that you can more easily assign the property.
Concatenating a string to form a collection of key-value pairs, very much like a query-string.
In the example you gave, this would mean storing something like:
var keyVals = 'route_markers' + '=' + str + '&';
document.getElementById('myHiddenProperties').value = keyVals;
When you want to assign another property to this string you do something like this:
keyVals = document.getElementById('myHiddenProperties').value;
keyVals += 'new_property' + '=' + myNewValue + '&';
document.getElementById('myHiddenProperties').value = keyVals;
In this way, if you want to remove a specific key-value pair, you split the stored value like this
var arrKeyVals = document.getElementById('myHiddenProperties').value.split('&');
You then have an array of key-value pairs.
If you want to retrieve a value from this array, or blank one of the values then loop through this array, splitting each into its key and value, like this:
for (var i = 0; i < arrKeyVals.length; i++) {
var keyVal = arrKeyVals[i].split('=');
var key = keyVal[0];
var val = keyVal[1];
if (key == name_of_key_sought) {
val = ''; //assign an empty string to this property to forget about it
}
}
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
No, the value property of certain HTML elements is just a string value. (And it only exists on certain elements, like input.) Assigning a new value to value will overwrite the previous value, not store it in an array.
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
This part of the question sort of goes away because of the answer to the first part, but you can clear the value property by assigning an empty string to it.
If by any chance you mean remove/hide the element itself (the text box) then you can have such code:
document.getElementById('rout_markers').style.display = 'none';
Otherwise the other answers here cover it all nicely.

Categories

Resources