Not able to retrieve key value - javascript

I have data in format
var data = "{key1=value1,key2=value2}"
I want to perform something like when I have key1 i should get value1 in return.
For example:
var val = data[key1];
//val value should be value1

There are a few issues here. The first is that your 'data' variable in its current form is just a string. You would need to remove the enclosing quotes, and replace your ' = ' with ' : ' which will make it a JavaScript object so you can index into it.
The second issue is that 'value1' in your object is not defined. You would either need to create another variable called 'value1' and initialize it, then stick it into your data object, but their are better ways to go about it if this is what you are trying to accomplish.
If you are just creating key/value pairs, then you could do something like:
var data = {key1:'value1',key2:'value2'};
You could then access the 'key1' value by doing the following:
var val = data['key1'];
or
var val = data.key1;
Here is a fiddle to illustrate how it works: http://jsfiddle.net/LxjN4/

Related

Click a button or a link to set as a default option using <select> another page? [duplicate]

I have a page1.html which contains set of data
{'key1':'value1','key2':'value2','key3':'value3'}
and a link
<a target='_blank' href='page2.html'>Click To Navigate</a>
which will navigate to page2.html.
I would like to ask how can I pass all the data above in page1.html to page2.html so that I can use them in page2.html.
What I tried to use is localStorage, but I can store only 1 set of data at a time, so if in my page1.html have many set of data, same key but different value they will be overlapped when I store them in localStorage, then I can not pass all these set of data to the page2.html.
Anyone got an idea?
Thank you so much
You can do it using Javascript, there's no restriction of which kind of object you can pass.
For instance, if you have several key-value objects:
var firstData = {
'key1' : 'value1',
'key2' : 'value2'
};
and
var secondData = {
'key1' : 'value3',
'key2' : 'value4'
};
you could enclose them using a Javascript array:
// This is on page1.html
var myData = [ firstData, secondData ];
and pass that array using localStorage.
Javascript on page1.html
// Set the variable
localStorage.setItem( 'objectToPass', myData );
Javascript on page2.html
// Get the variable
var myData = localStorage['objectToPass'];
localStorage.removeItem( 'objectToPass' ); // Clear the localStorage
var firstData = myData[0];
var secondData = myData[1];
alert('firstData: ' + firstData + '\nsecondData: ' + secondData);
If you want to use javascript to do this, you can do the following (explains it really well)
- https://www.boutell.com/newfaq/creating/scriptpass.html
Also, you can use HTML5 to pass objects from a page to another page of your choise. In order to do this, you would create a session like this:
sessionStorage.setItem('key', 'value');
And then to read the session you would do this:
sessionStorage.getItem('key');
This is a really good example on a webpage on how this can be achieved:http://demos.w3avenue.com/html5-unleashed-tips-tricks-and-techniques/sample-09-sessionstorage-demo.html
You can use the localstorage with JSON method (JSON.parse) to parse a JSON string and construct the JavaScript value or object described by the string. The reverse operation is accomplished by the other method (JSON.stringify) to convert a JavaScript object or value to a JSON string.
javascript on the first page:
var data = {'key1':'value1','key2':'value2','key3':'value3'};
localStorage.setItem("object_name",JSON.stringify(data));
javascript on the second page.
var data = localStorage.getItem("object_name");
localStorage.clear(); //clean the localstorage
var value1 = JSON.parse(data).key1;
var value2 = JSON.parse(data).key2;
So now value1 and value2 in the second page contain the value of value1 and value2 of the first page.

Javascript create a mapping of array values

I am working on a project where I give a user the ability to create their own email templates and insert tags into them as placeholder values that will eventually replaced with content.
The tags are in the format of [FirstName] [LastName]
I am trying to figure out the best approach to create a function that maps these tags to their values.
For example (Psuedo code):
function convertTags(message){
// Convert all instances of tags within the message to their assigned value
'[FirstName]' = FirstNameVar,
'[LastName]' = LastNameVar
// Return the message with all tags replaced
return message;
}
I assume I could do something like the following:
function convertTags(message){
message = message.replace(/[FirstName]/g, FirstNameVar);
message = message.replace(/[LastName]/g, LastNameVar);
return message;
}
I am just trying to come up with a clean way to do this, preferably in an array/mapping style format that I can easily add to.
Any recommendations on achieving this?
You're on the right lines. You just need to generalise your REGEX to match all params, not specifically 'firstname' or some such other hard-coded value.
Let's assume the replacers live in an object, replacers.
var replacers = {
'foo': 'bar',
'something-else': 'foo'
};
And here's our template:
var tmplt = 'This is my template [foo] etc etc [something-else] - [bar]';
For the replacement, we need iterative replacement via a callback:
tmplt = tmplt.replace(/\[[^\}]+\]/g, function(param) { //match all "[something]"
param = param.replace(/\[|\]/g, ''); //strip off leading [ and trailing ]
return replacers[param] || '??'; //return replacer or, if none found, '??'
});
The value of tmplt is now
This is my template bar etc etc foo - ??
Let's say you have an object like this:
var tagMapper: {};
In this object you can add anything you want as key-value pairs, example:
function addTag(key, value){
key = "__prefix__" + key;
tagMapper[key] = value;
}
addTag("key1", "value1");
The difference between an object and an array in javascript is that one uses named indexes while the other uses numbered indexed to set and retrieve data.
Now every time your user adds a new tag, you just add a new key-value pair to this object by calling the addTag function, then to replace those keys in your template just loop over the object as such:
for (var key in tagMapper) {
if (tagMapper.hasOwnProperty(key)) {
template = template.replace(key, tagMapper[key]);
//key here has value "__prefix__key1" and maps to "value1" from our example
}
}
The prefix was added to ensure the script doesn't replace an undesirable string from our template. Your tag format may be sufficient if you are sure the template doesn't contain any [] tags containing the same key as one in the tagMapper object.

JavaScript Array Issue with data['sax']

I have a confusion of what this array can hold. Also, I want to know how it assigns the values to the variable set.
Can someone give me an example of data['sax'] please and explain me the loop below?
for(var x = 0; x < data['sax'].length; x++){
var set = data['sax'][x];
Then what does this mean ?
id : set.saxID,
name : set.symbol
What you have here is an array that is being looped through. data['sax'] will be something along the lines of the following:
var data = {
sax: [
{
saxID: 1,
symbol: 1
},
{
saxID: 2,
symbol: 2
}
]
}
As you can see in the example above, sax is an array which contains multiple objects. What happens when you loop over it, is that it accesses one of the objects inside the array. So data['sax'][0] will give you the object with saxID: 1.
Using the variable set to temporarily store the data in; you can access the data of data['sax'][0] as set. So data['sax'][0].saxID becomes set.saxID. It is somewhat of a shorthand version of accessing the data.
What happens with id: set.saxID, is that the values get assigned to a new object. Which will be something like the following.
var newSax = {
id: set.saxID
}
You are basically transferring data from one object to another.
Explaining the code
var set = data['sax'][x];
Here you are creating a variable called set and assigning it a value from data['sax'][x].
data['sax'] this might look like a array But Its Not, to access value of a array we use index but here its a string. This is another way of accessig a property value of a object. So data is a object with one of its property being sax. That means
data = {sax: somevalue};
Now we have,
data['sax'][x] So as you know data['sax'] is a object and then this [x] , here x is not a string its a variable and it holds the Number value (0,1,2,3...) , it means your data['sax'] value is a array since we are accessing from index.
So from the above analysis your data['sax'] will be in this format.
Array
data = { sax : ["someValue","someValue"]}
So variable set will be
var set = "someValue"; // if x = 0, as in the first loop
Now coming to the code
id : set.saxID,
name : set.symbol
set.saxID this is used if the set is an object. In Jquery to retrieve the value of a property in the object you use the . operator with property name (or by the property name as seen above). So the code means set is a object with two properties saxID and symbol. So your set object will be like
set = { saxID: 123, symbol = "TEST"}
That also means that your data value be
data = { sax : [{saxID: 123, symbol = "TEST"},{saxID: 123, symbol = "TEST"}]}
Let me know if I was clear

How does Object.keys work when applied to a Javascript variable?

I have some code in my application like this:
var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];
Can someone please explain what the Object.keys part of this code is doing and give me some idea what the data.datamodelState object looks like.
Right now it is my understanding that this code is not working but the code around it is not so I can't debug to find out.
Object.keys() returns array of keys of that object. In your code, you are accessing first element of array. i.e. first key of data.data.modelState.
This code is just to get the value of first key of data.data.modelState.
For Example
Suppose
data.data.modelState={tmpkey:"Some Value"}
var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];
console.log(Object.keys(data.data.modelState)[0]); //will Print ["tmpkey"]
console.log(msg); //It will print "Some Value";
You can access any key of object using []; And here you are accessing first key.
var msg = data.data.modelState[Object.keys(data.data.modelState)[0]];
This will become
var msg = data.data.modelState[["tmpkey"][0]];
And it will become
var msg = data.data.modelState["tmpkey"]; //Simply it will return value of tmpKey property.

how to pass a dynamic key value from a string in mongo data base

I try to dynamically access a field in mongo database.
The target field is given by this line:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
Where
Session.get('contextLayout') could be either a string or an _id of a collection(eg. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor).
I don't know how to access the value.
I tried this code:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
var tempStore ={};
tempStore['target']=contextTarget;
var newTarget = tempStore.target;
console.log(newTarget);//return the correct value
var color = customConfiguration.findOne({'author':auth}).newTarget;
console.log(color);//return undefined
It doesn't work. I suppose that it's because the newTarget variable is a string because if I directly write the expected result in the console, it works.How can I do?
EDIT.
like said BraveKenny:
var color = customConfiguration.findOne({'author':auth})[contextTarget];
In fact, it was not necessary to pass by the object tempStore. With the square brackets keys are properly sent. I had already try it but with a dot before the square bracket.
#Michael: For the schema, I don't have a schema for this collection, because the key names are dynamically created.
Thanks a lot.
If I understand correctly, in the end, you want to get a variable attribute of your customConfiguration object, which name is contained in newTarget.
Maybe try this instead:
var color = customConfiguration.findOne({'author':auth})[newTarget];
Basically when you type:
someObject.toto = 'someValue';
var someAttribute = 'toto';
console.log(someObject.someAttribute); //undefined
console.log(someObject[someAttribute]); // 'someValue'
JavaScript will always assume someAttribute is an attribute of someObject when it's called with a dot notation. Not a variable set in the scope. If you want the value of an attribute toto which is contained in a string variable (in my case, someAttribute), you have to pass this variable as an index, like this:
console.log(someObject[someAttribute]); // 'someValue'
It would be helpful if you could describe the schema of the collection customConfiguration. I just guess that it contains a collection of documents with just one property each (e.g. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor) and you are interested in the one document with the correct property name to read the property value. So I guess, in JSON notation the collection looks something like this:
[
{"userHomeBackgroundColor": "red"},
{"56xhPYg8w3Qtv9xPLBackgroundColor": "green"},
{"someOtherConfigProperty" : "someOtherValue"}
]
If this assumption is correct, I would replace your original line
var color = customConfiguration.findOne({'author':auth}).newTarget;
With something like this:
var selector = {}; // Empty selector object for findOne
selector[contextTarget] = // Add dynamic property and as its value
{$exists: true}; // an object with an $exists-property
// with value true
// now find the (first) configuration document having the dynamic property
var configDocument = customConfiguration.findOne(selector);
// read the value of the dynamic property of the configuration document
var color = configDocument[contextTarget];
But to verify this, I need more background about the schema of the collection customConfiguration. You might also want to check the documentation of $exists (http://docs.mongodb.org/manual/reference/operator/query/exists/#op._S_exists) and findOne() (http://docs.mongodb.org/manual/reference/method/db.collection.findOne/) in the documentation.
If, however, the collection customConfiguration contains one configuration document for each author, change your line to just this:
var color = customConfiguration.findOne({'author':auth})[newTarget];
This solution has been described in a previous answer.

Categories

Resources