chrome.storage.local.get results in "Undefined" when called - javascript

I'm building a chrome extension, and I needed to save some data locally; so I used the Storage API . I got to run the simple example and save the data, but when I integrated it with my application, it couldn't find the data and is giving me "Undefined" result.
Here is my Code:
function saveResults(newsId, resultsArray) {
//Save the result
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.set({ id : resultsArray[i] });
}
//Read and delete the saved results
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.get(id, function(value){
alert(value.id);
});
chrome.storage.local.remove(id);
}
}

I am not certain what type of data you are saving or how much, but it seems to me that there may be more than one newsId and a resultsArray of varying length for each one. Instead of creating keys for each element of resultsArarry have you considered just storing the entire thing as is. An example of this would be:
chrome.storage.local.set({'results':[]});
function saveResults(newsId, resultsArray) {
// first combine the data into one object
var result = {'newsId':newsId, 'resultsArray':resultsArray};
// next we will push each individual results object into an array
chrome.storage.get('results',function(item){
item.results.push(result);
chrome.storage.set({'results':item.results});
});
}
function getResults(newsId){
chrome.storage.get('results', function(item){
item.results.forEach(function(v,i,a){
if(v.newsId == newsId){
// here v.resultsArray is the array we stored
// we can remove any part of it such as
v.resultsArray.splice(0,1);
// or
a.splice(i,1);
// to remove the whole object, then simply set it again
chrome.storage.local.set({'results':a});
}
});
});
}
This way you don't need to worry about dynamically naming any fields or keys.

First of All thanks to Rob and BreadFist and all you guys. I found out why my code wasn't working.
Storage.Set doesn't accept the key to be an 'integer' and even if you try to convert that key to be a 'string' it won't work too. So I've added a constant character before each key and it worked. Here's my code.
function saveResults(Id, resultsArray) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.set({key : resultsArray});
}
function Load(Id) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.get(key, function(result){
console.debug('result: ', result.key);
});
}

Related

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}

Iterating over and comparing properties of two arrays of objects

I have set up a HBS helper which takes in two arrays of objects (users privileges). What I want to do is compare them and inject back into the template the privileges the user does and doesn't have.
Presently I can compare the names of the privileges with the following code:
hbs.registerHelper('selected', function(option, value){
var i;
var j;
var privName;
var userPriv;
var privObj = new Object();
var privArray = [];
for(i in option){
console.log('each ' + JSON.stringify(option[i]));
privName = option[i].privname;
for (y in value){
if(privName == value[y].privname){
userPriv = value[y].privname;
console.log('user has the following privileges', value[y].privname);
privObj = new Object();
privObj.name = userpriv;
privObj.id = value[y]._id;
privObj.state = 'selected';
privArray.push(privObj);
} else if (privName != value[y].privname){
console.log('user doesnt have priv ', privName);
privObj = new Object();
privObj.name = option[i].privname;
privObj.id = option[i].id;
privObj.state = '';
privArray.push(privObj);
}
}
}
console.log('privileges array ', privArray);
return privArray;
});
This works OK when the user only has one privilege, however when the user has more than one, for example two privileges, it returns the privileges twice. If the user has 3, thrice and so on. I know this is because the array is looping again because their are 2, 3 etc in the .length. However I can't seem to find an adequate solution.
Any help?
P.S. it would be nice if the Array.includes() method allowed you to search object properties.
The problem creating new objects the way you did is that for each property you add to your privilege-entity you will have to return to that function and set that property as well. You can instead just add/alter the state property of the existing objects:
hbs.registerHelper('selected', function(option, value) {
var names = option.map(function(opt) {
return opt.privname;
});
value.forEach(function(val) {
val.state = names.indexOf(val.privname) >= 0 ? 'selected' : '';
});
return value;
});
Basically:
The variable names is being mapped to be an array only with the privnames. You can check by using console.log(names).
The Array.forEach() function is helpful in this case because you just need to iterate over each object inside value and set its state-property.
To check if the privname exists, you just need to check the index in the previous names-mapped-array. For such a simple thing I used ternary operator (?:).
Finally, you return value, which is the array containing the objects you had updated.

Redis key is not creating properly

I am new to Redis and am trying to hmset some values by generating my own keys to store and access it. But for some reason, key is not being created properly and the data's are overwritten. Below is my code for it,
locations.forEach(function(location) {
var key = location.id;
console.log(key); // all keys are correct
client.hmset("locations", { key: location }); // using redis-jsonify
});
The data am getting is only one of the whole response since the key is actually saved as key itself.
For example:
I tried using client.incr('id', function(err, id) {}); but same problem.
Need help with this. Thanks in advance.
From the Redis HMSET doc:
Sets the specified fields to their respective values in the hash
stored at key. This command overwrites any existing fields in the
hash. If key does not exist, a new key holding a hash is created.
HMSET is used to set all the values at once.
If you want to set one hash field at a time, use HSET:
locations.forEach(function(location) {
var key = location.id;
client.hset("locations", key, location); // or `JSON.stringify(location)` if redis-jsonify doesn't work as expected
});
Closures to resuce
for (var i = 0; i < locations.length; i++) {
(function(i) {
console.log('locations: ' + location[i]);
client.hmset("locations", { i: location[i] });
})(i);
}

Do a query for every loop item and wait for result

I am making a CloudCode function that returns all users that are matching to my settings. In this function I am looping through a list of users and I need to get their settings in order to see if I should return them. The only problem is that the loop doesn't wait for the query to finish.
How can I get the Settings object for every user in the loop, check if the settings are correct and then push them in an array and return the array when the loop has finished?
The code I am using now:
for (var i = 0; i < connectResults.length; i++) {
var connect = connectResults[i];
for (var j = 0; j < matchResults.length; j++) {
var match = matchResults[j];
if (connect.get("sendBy").id == match.id) {
var indexOf = matchResults.indexOf(match);
matchResults.splice(indexOf, 1);
} else if (connect.get("receivedBy").id == match.id) {
var indexOf = matchResults.indexOf(match);
matchResults.splice(indexOf, 1);
}
if(typeof match.get("settings") != 'undefined') {
var settingsQuery = new Parse.Query("Settings");
settingsQuery.equalsTo("objectId",match.get("settings").id);
settingsQuery.find({
success: function(setting) {
console.log(match.get("username") + " " + setting.get("radius"));
}
});
}
}
}
response.success(matchResults);
Instead of querying all users and attempting to match their settings, I would instead query all users using the setting as a query constraint. In other words, tell the database that you want it to return all the users with the right settings.
var usersQuery = new Parse.Query("Users");
//Below, "settings" is the column name in your Users table
usersQuery.equalTo("settings", /* Settings value you are matching */);
usersQuery.find({
//...
});
You might need a containedIn query if there are multiple setting possibilities. See the docs for an example: https://parse.com/docs/js/guide#queries-query-constraints
Good luck! :)

js/jQuery - Converting array to string

The 2 drop downs I'm using to store into local storage are storing as an array.
How could I convert it where if any arrays are detected then convert it and store it as string instead?
Something like this?
if( Object.prototype.toString.call( value ) === '[object Array]' ) {
value.toString();
}
Please see my fiddle:http://jsfiddle.net/3u7Xj/137/
Showing being stored as:http://i.imgur.com/L78kGE7.jpg
local storage function:
save = function () {
$('input, select, textarea').each(function () {
var value = $(this).val();
var name = $(this).attr('name');
if($(this).hasClass('checkers')){
value = $(this).is(":checked")
if(value){
value='on';
}else{
value='off';
}
}
if(this.name.match(/^multiselect_/)){//removes buggy append
return false;
}
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
if (localStorage.getObj('Surveys') != null) {
Surveys = localStorage.getObj('Surveys');
}
Surveys[$('#FirstName').val() + '.' + $('#LastName').val()] = Survey; //store in big list
localStorage.setObj('Surveys', Surveys);
}
The easiest way to convert an array to a string is array.join(). Called just like that you get a comma-delimited string that contains all of the elements in the array. If you provide a separator (such as array.join('|')) you get a string that is delimited with the separator you provided. Where this fits into your saving function is up to you.
I would recommend using jQuery.encodeJSON()
http://forum.jquery.com/topic/jquery-encodejson
This way you can store your object as a JSON string.
You can then get your object back using the jQuery.parseJSON() function.
https://api.jquery.com/jQuery.parseJSON/
If i understood it right, i guess this could work:
Use Array.isArray method and then use JSON.stringify to turn the array into a string.
for (var key in this) {
//console.log(key, this[key]); //log to console
if($.isArray(this[key])) {
this[key] = this[key].join(':'); //change array to string separated by :
}
}

Categories

Resources