accessing values form string in jquery - javascript

I am returning string from database in following
format =opRadio=1&selSchool=0&opRadio2=1&selClg=0
What I want to access values like 1 or 0 in javascript or jQuery. I mean I want to retrieve 1 when I pass opRadio.
I tried by encoding string into json but no luck.
Thanks in advance.

Try this :You can use split('&') to seperate key value pair and then use split('=') to get key and value to put it in map. use map to retrieve values by passing key
var dbString = "opRadio=1&selSchool=0&opRadio2=1&selClg=0";
dbString = dbString.split('&');
var map = {};
for(var i=0;i<dbString.length;i++)
{
var keyValue = dbString[i].split('=');
map[keyValue[0]] = keyValue[1];
}
//to read value by passing key
alert(map['opRadio']);

Related

Get object from Local Storage Angular 8

I have a localstorage which is storing some data. I am trying to get the data in a component using localStorage.getItem('id'); but it is undefined. The problem is, localStorage is storing id in a strange format. It is stored like abcabcabc.id Now there are multiple such parameters in localStorage and for each logged in user the string abcabcabc changes. How can I still get id value. Can I compare string or something to get values? Like if it contains string .id only read that value? If yes, can you explain how would that be achieved?
localstorage:
abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg
Since you do not know the exact key stored in localStorage fetch all of them and then iterate over it. Next, match part of the key that you know i.e id as illustrated below:
// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };
// iterate over them
for (const index in localStorageKeys) {
// see if key contains id
if (index.includes('id')) {
// fetch value for corresponding key
console.log(localStorageKeys[index]);
}
}
localStorage sets data as a map of key-value pairs, so :
var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string
localStorage.setItem('id', JSON.stringify(id));
now you get the data by:
var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));
This is how you would normally do it, but since I don't know how you had set the data, you would instead get the data by:
var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);

Problem with converting array to json in JavaScript

I have this code:
var fields = [];
$('input').each(function(){
var name = $(this).attr("name");
fields[name] = $(name).val();
});
And I want convert the fields variable to a json string, but when I use JSON.stringify I get (using console.log) only: []
How can I simply convert array fields to a json string?
Ok problem was on the following line:
fields[name] = $(name).val();
I changed name to this:
fields[name] = $(this).val();
And worked like i want it to.
If you want text strings like field names (as opposed to numbers) as property names, you want an object, not an array. Initialize fields to {} instead of [].
The JSON serialization of an array will only include the properties whose keys are numbers, from zero up to the value of .length (minus one).
Just made one correction, use object instead of array:
var fields = {};
$('input').each(function(){
var name = $(this).attr("name");
fields[name] = $(name).val();
});

What query can i use to fetch data from local storage of selected key value

I need to store a lot of data in local storage for my app. I am successful in storing that. Now i need to fetch data in an array but of the selected key/values and not all or just 1 of them. I have named these key as "section"+id as seen below, need to select these in an array.
localStorage.getItem(key) will return the data for the key you provide. Data from localStorage is serialized so you need to parse it with JSON.parse(data) into a plain JS object and then you can work with it as any other object.
You can only get a single item with localStorage.getItem so if you want to get multiple items in an array you'll have to loop and get each one individually and put them in an array.
Maybe something like this:
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
return JSON.parse(localStorage.getItem(key));
});
First, we get all the "section###" keys with the filter function. Then we create a new array with the data for each corresponding item using the map function.
Try this code. I have edited it.
var keys = [];
var data = [];
for (var key in localStorage) {
if (key.indexOf("section") > -1)
keys.push(key);
}
for (var i in keys) {
data.push(localStorage.getItem(keys[i]))
}

Parse the JSON Object with Index or position instead of keyname using Jquery?

My Existing Code and Explanation
Working Fine, But I want to Create a template like Its should read JSON Data that Having keys in any name, I am Always reading data from JSON object in 2nd Position
Now I read the JSON that passed in the argument (data) inside that using the for loop extract single object in group, after that get the data using key(Module_Name).. I know the key(Module_Name) is always present in second position only, Now its Working Fine with keyname rather i want to fetch the data using position, that also used as template in my other modules
/* render Screen Objects */
screenRenderer.displayScreens = function(data)
{
screenRenderer.renderLayout(function(cont, boo)
{
if (boo)
{
for(i=0;i<data.length;i++)
{
var buttons = "<button class='screen_button'>"+data[i].Module_Name+"</button>";
$("#screen-cont").append(buttons);
}
}
else
{
scr_cont.show();
}
})
}
This is My Requirement, kindly awaiting suggestions, answers..
Thanks in Advance
You can use the function Object.keys(obj) to get all keys of an object as array, which you can access with an Index and than use the String you get to access the property.
So it could look like this:
var obj = data[i];
var keys = Object.keys(obj);
var result = obj[keys[1]];
Hope this is what you want.

Convert Javascript string or array into JSON object

I have a JavaScript variable with comma separated string values - i.e. value1,value2,value3, ......,valueX,
I need to convert this variable's values into a JSON object. I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search)
Please help me to sort this out.
What you seem to want is to build, from your string, a JavaScript object that would act as a map so that you can efficiently test what values are inside.
You can do it like this :
var str = 'value1,value2,value3,valueX';
var map = {};
var tokens = str.split(',');
for (var i=tokens.length; i--;) map[tokens[i]]=true;
Then you can test if a value is present like this :
if (map[someWord]) {
// yes it's present
}
Why JSON? You can convert it into an array with split(",").
var csv = 'value1,value2,value3';
var array = csv.split(",");
console.log(array); // ["value1", "value2", "value3"]
Accessing it with array[i] should do the job.
for (var i = 0; i < array.length; i++) {
// do anything you want with array[i]
}
JSON is used for data interchanging. Unless you would like to communicate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.
JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. Read more about it
All about JSON : Why & How
Cheers!!
JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a comma separated list in to JSON format. You need keys to assign.
Example,
[
{"key":"value1"},
{"key":"value2"},
{"key":"value3"},
...
{"key":"valueX"}
]
I think for your requirement, you can use Array.

Categories