Stringify a key value pair in Javascript and session storage - javascript

I have code as follows:
var employee = {};
employee["fullname"] = document.userForm.fullname.value;
employee["license"] = document.userForm.license.value;
employee["address"] = document.userForm.address.value;
employee["dob"] = document.userForm.dob.value;
employee["city"] = document.userForm.city.value;
employee["state"] = document.userForm.state.value;
employee["zip"] = document.userForm.zip.value;
employee["sex"] = document.userForm.sex.value;
sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));
Is it correct to store it this way? Also if this is correct , how do I retrieve the information using getItem?

retrieve it with :
var mySessionData = sessionStorage.getItem("session");
var mySessionDataParsed = JSON.parse( mySessionData );
edit
Is it correct to store it this way
//sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));
sessionStorage.setItem("session", JSON.stringify( employee ) );
// this way is suffisant !
// but if you prefer an array you can go with your way too !

You can also use dot and/or bracket notation.
sessionStorage["session"] = JSON.stringify({"employees": [employee]});
// or
sessionStorage.session = JSON.stringify({"employees": [employee]});
and the same goes for the right hand side of an assignment.
data = sessionStorage["session"];
// or
data = sessionStorage.session;
No need to invoke the get and set item methods as you just add needless overhead.

Related

How to amend a new key to existing object using session storage

I have below piece of code
addToFilterCriteriaTree(componentData) {
let id = componentData.props.data.id;
this.state.filterCriteriaTree[id] = componentData.criteria;
}
Instead of state ,I want to create a object 'filterCriteriaTree' using setStorage and add a new key to it
I've changed the parameters since it's cleaner to supply only the data needed for the function to do it's job rather than the entire object.
addToFilterCriteriaTree(id, criteria) {
let currentFilterCriteriaTree = JSON.parse(sessionStorage.getItem('filterCriteriaTree')) || {};
currentFilterCriteriaTree[id] = criteria;
sessionStorage.setItem('filterCriteriaTree', JSON.stringify(currentFilterCriteriaTree);
}

Autodesk Forge How to get dbid from name

I have an extension which loads a docking panel with a text field and a button. The functionality of this button would be to display the DB-ID of the item name given in the text field.
Something like:
Rubber = 2130
where Rubber is the input and 2130(db-id) will be the output
How can I achieve this?
Thanks in advance.
Would suggest using .search() method, which is a supported way:
viewer.search('Rubber', function(dbIds){
// here the dbIds is a list of dbIds, you can handle it
callback(dbIds); // handle the results async
}, function(error){
// handle errors here...
}, ['name'] /* this array indicates the filter: search only on 'Name'*/
)
And look here on how to improve performance on search.
There is no such API available currently, but a workaround can be used in this case. It's shown as the following:
//-- For the element type or element category like "Floor [" or "Floor"
var it = viewer.model.getData().instanceTree;
var strIdx = it.nodeAccess.strings.indexOf( "Floor [" );
// var strIdx = it.nodeAccess.strings.indexOf( "Floor" );
var nameIdx = it.nodeAccess.names.indexOf( strIdx );
for( var key in it.nodeAccess.dbIdToIndex ) {
if( it.nodeAccess.dbIdToIndex[key] === nameIdx ) console.log( key )
}
//-- For element name like "Floor[766598]":
var it = viewer.model.getData().instanceTree;
var eidIndex = it.nodeAccess.nameSuffixes.indexOf( 766598 );
for( let key in it.nodeAccess.dbIdToIndex ) {
if( it.nodeAccess.dbIdToIndex[key] === eidIndex ) console.log( key )
}
P.S. Since this is just a workaround, not the formal solution. You would have to use it at your own risk.
If you want to avoid using the search() method, you could also create your own Object that maps the name to ID's. This is a temporary workaround until Autodesk implements its own method.
var instanceTree = viewer.model.getData().instanceTree; // Get model tree
var allDbIds = Object.keys(instanceTree.nodeAccess.names); //get array of all ID's
var forgeNameMap = {} //Empty array for mapping names
allDbIds.map(function(id) {
forgeNameMap[instanceTree.getNodeName(id)] = id
})
let rubberID = forgeNameMap["Rubber"]

How to access value of variable in Mongo?

var a = "act";
db.s.findOne( {
BrandId: doc.BrandId,
a : {$exists:false}
} ).a;
I try to pass the value of variable "a" to my MongoScript. But it looks it can not be simply used. anyone can help?
Build your query step by step and do not use . use [] instead
var a = 'act';
var query = {BrandId: doc.BrandId};
query[a] = {$exists:false};
db.s.findOne(query)[a];
Note:
query.act == query['act'].
Just some javascript tricks.

HTML5 Local Storage with saved integers and variables

I'm trying to achieve a function that makes the user able to save a mathematical formula that uses static variables that I've already created and save them with Local Storage.
Then the script fetches that formula from the Local Storage, does the math and displays the results on a table.
I have everything in order, except the fetching part;
as localStorage.getItem() returns a string, and converting it with parseFloat()/parseInt() only returns the first integer or NaN.
Both of this messes up the expected the results.
Is there any way I can get Objects from localStoage that contains both integers and variables?
Heres an example of a formula that should work, fetched by 5 localStorage.getItem() requests.
avgFrags*250
avgDmg*(10/(avgTier+2))*(0.23+2*avgTier/100)
avgSpots*150
log(avgCap+1,1.732)*150
avgDef*150
Any ideas or alternatives?
EDIT:
Each line represents the output of a getItem() request;
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
form_spot = localStorage.getItem('formula_spot');
form_cap = localStorage.getItem('formula_cap');
form_def = localStorage.getItem('formula_def');
localStorage store in a key-value store where every value is pushed to a string. If you are certent that you are handling "integers" you can push the string to a number:
var avgFrags = +localStorage.getItem('avgFrags'); // The + infront pushes the string to number.
I'm not completely sure that I understand your question.
(+"123") === 123
You can convert easily convert your strings to functions if you know the variable names before hand using Function(). The first parameter(s) are your function arguments and the last is your function body.
var func1 = Function('avgFrags', 'return avgFrags * 250;');
This is equivalent to:
function func1(avgFrags) {
return avgFrags * 250;
}
Known Function Signature
If you know what variable names will be used for each item in local storage then it should be easy for you to do what you want with function:
// from your edited question
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
// ... create functions
var fragsFunc = Function('avgFrags', form_frg );
var dmgFunc = Function('avgDmg', 'avgTier', form_dmg );
// ... get frags
var frags = fragsFunc (10); // frags = 2500; // if sample in storage
Unknown Function Signature
Now if you have a limited amount of variable names and you don't know which ones will be used with each function then you can do something like:
var avgFrags, avgDamage, avgTier, avgSpots, avgCap, avgDef;
// ... get from storage
form_frag = localStorage.getItem('formula_frag');
form_dmg = localStorage.getItem('formula_dmg');
// ... create functions
var fragsFunc = Function('avgFrags', 'avgDamage', 'avgTier', 'avgSpots', 'avgCap', 'avgDef', form_frag);
var dmgFunc = Function('avgFrags', 'avgDamage', 'avgTier', 'avgSpots', 'avgCap', 'avgDef', form_frag);
// ... get frags, only the first argument is used, but we don't know that.
var frags = fragsFunc (avgFrags, avgDamage, avgTier, avgSpots, avgCap, avgDef); // frags = 2500; // if sample in storage
You can make this simpler by having just one variable passed into the function which is an object that holds all of the arguments that can be passed to the function. Just have to make sure that the function writer uses that object.
var settings = {
avgFrags: 10,
avgDamage: 50,
// ...
};
var fragsFunc = Function('s', 's.avgFrags * 250');
var frags = fragsFunc (settings);
Getting parts with an regex
I am assuming that the above will get the job done, that you don't really want an object with variable names and numbers and operators.
If you just need the variable names and numbers (and operators) you can use a regex for that.
([a-z_$][\w\d]*)|([0-9]*\.?[0-9]+)|([^\w\d\s])
You can use that to create an array with each part. Also each part is grouped so you know which is a variable name, which is a number, and which is an other (parenthesis or operator)
var re = /(\w[\w\d]*)|([0-9]*\.?[0-9]+)|([^\w\d\s])/g,
match,
results;
while ((match = re.exec(localStorage.getItem('formula_frag'))) {
results.push({
text: match[0],
type: (match[1]) ? 'var' | (match[2]) ? 'number' : 'other'
})
}
You can view the output of the regex with your sample data using REY.
Yes you can set Objects in localstorage
Here is the fiddle for that - http://jsfiddle.net/sahilbatla/2z0dq6o3/
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
$(function() {
localStorage.setObject('x', {1: 2, 2: "s"})
console.log(localStorage.getObject('x'));
});

own array + jQuery.serializeArray() + post as json

I get data is undefined, i guess i can't ['productId'] in an array, but i think i need this structure in the json, i tried a couple of variation but it never was, what i needed
i just want to send a json via ajax.
jQuery(':checked').each(function(i){
data[i]['productId'] = jQuery(this).parent().find('.productId').val();
jQuery(this).parent().find('.attrGrp').each(function(j){
data[i]['attrGrps'][j]['uid'] = jQuery(this).find('.active').attr('id');
data[i]['attrGrps'][j]['amount'] = jQuery(this).parent().find('.amount').val();
});
});
jQuery.post(newSession, {json: data.serializeArray()});
is there any better way for doing it? or how can i make it work?
help appreciated ;/
You need to initialize arrays and objects before using them. String indexes are only possible with objects. Try this:
var data = [];
jQuery(':checked').each(function(i)
{
data[i] = {};
data[i].productId = jQuery(this).parent().find('.productId').val();
data[i].attrGrps = [];
jQuery(this).parent().find('.attrGrp').each(function(j)
{
data[i].attrGrps[j] = {};
data[i].attrGrps[j].uid = jQuery(this).find('.active').attr('id');
data[i].attrGrps[j].amount = jQuery(this).parent().find('.amount').val();
});
});
Alternatively you could use jQuery().serialize, post everything in the form and sort it out on the server.

Categories