Unexpected string from Chrome storage set - javascript

I'm trying to set in localStorage after checking if the key already exists, but I'm getting this error. Anyone know what is happening and how can I solve it?
chrome.storage.sync.get($div.attr('id'),function(items){
var lastError = chrome.runtime.lastError;
if (lastError) console.log($div.attr('id')+" does not exist.\n", lastError);
else chrome.storage.sync.set({$div.attr('id'):$div.html()}, function(){}); //I'm having the error from this line
});
Uncaught SyntaxError: Unexpected string
Edit:
Apparently this has something to do with the attr('id')
because I created a variable and then the problem was gone. Thank you anyway.
This is working:
var myobj = {}, key = $div.attr('id');
myobj[key] = $div.html();
chrome.storage.sync.get(key,function(items){
var lastError = chrome.runtime.lastError;
if (lastError) console.log(key+" does not exist.\n", lastError);
else chrome.storage.sync.set(myobj, function(){}); //The error is gone
});

The problem isn't with attr itself, but in the way you're trying to dynamically set a key on a new object literal using it:
{$div.attr('id'):$div.html()}
You can't create an object literal in this way. Keys in the creation of an object literal must be string or numeric literals.
To attach a dynamic key to an object you'd rather do something like this:
else {
var obj = {}, key = $div.attr('id');
obj[key] = $div.html();
chrome.storage.sync.set(obj, function(){});
}

Related

JSON [object Object] Data Pulling (unable to get object data)

Introduction
Hello, I am having a problem where I pull API data using JSON but then I have problems showing or working with the Data.
My Code
function pullingInformation () {
var data = new XMLHttpRequest();
data.open('GET', 'RANDOM URL CANT SHOW API KEY');
data.onload = function () {
if (data.status >= 200 && data.status < 400) {
// Different types of JSON.random(). Examples are: parse() and stringify();
var ourData = JSON.stringify(data.responseText);
var tempOurData = JSON.parse(ourData);
tempHTML = WeatherHTML(tempOurData);
$('#DivID').html(tempHTML);
}
else {
$('#DivID').html('Server failure, please try again!');
}
};
data.onerror = function () {
$('#DivID').html('Connection error ocurred, please try again!');
}
}
function WeatherHTML (data) {
tempHTML = data;
console.log(tempHTML);
console.log(tempHTML.coord);
return tempHTML.coord;
}
Problem
When I console.log() tempHTML I get the entire code from the API but if I try taking just a specific bit of the code which looks like this:
{"coord":{"lon":45.1,"lat":12.45},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main:{"temp":298.508,"pressure":1031.37,"humidity":97,"temp_min":298.508,"temp_max":298.508,"sea_level":1031.75,"grnd_level":1031.37},"wind":{"speed":5.72,"deg":92.5012},"clouds":{"all":12},"dt":1515515421,"sys":{"message":0.0155,"country":"YE","sunrise":1515468218,"sunset":1515509418},"id":6940814,"name":"Craiter","cod":200}
for example tempHTML.coord returns me 'undefined'. What am I doing wrong and where is my mistake? Am I simply pulling the information wrong or calling the object in a non-correct method?
var ourData = JSON.stringify(data.responseText);
Here you take the string of JSON which represents an object and convert it to a string of JSON which represents a string of JSON which represents an object.
var tempOurData = JSON.parse(ourData);
Then you reverse that, giving yourself the original string of JSON.
This is entirely pointless and you would have got the same effect with:
var tempOurData = data.responseText;
tempHTML = WeatherHTML(tempOurData);
Then you pass it through a function, which logs it, assigns it to a global, then returns it. You then assign it to the same global, overwriting the identical string already there.
tempHTML.coord
Then you try to read the coord property of the string. It is undefined because strings don't have a coord property.
You need to parse the original JSON to turn it into an object. Then you can access its properties.
if (data.status >= 200 && data.status < 400) {
var ourData = JSON.parse(data.responseText);
console.log(ourData.coord);
}
In addition, you need to fix your JSON. It is invalid. You are missing a quote. JSON Lint will highlight exactly where.
$('#DivID').html(tempHTML);
jQuery's html method expects to be passed a string, jQuery object or DOM object.
{"lon":45.1,"lat":12.45} is a plain object and not one of the above data types. jQuery will treat it as if it were an empty string.

Creating property for an object during run time

I am trying to create a property for an object like shown below but if I type Object.keys(window.data) I am getting the object name as DENTAL[object Object]
Method goes like this:
function GetAppliedFilterValue(TabName, filter) { //TabName="DENTAL", filter.CoverageId = 10
var property = TabName.concat(String(filter.CoverageId));
window.data[property.toString()] = {};
Where am I going wrong?
PS. the coverageId property of object filter is Number type
Thank you #Bergi, your suggestion helped me that worked.
My implementation:
function GetAppliedFilterValue(TabName, filter) {
var property = TabName + String(filter.CoverageId);
window.data[property.toString()] = {};

How to get the "typeof" in JavaScript for a json message

When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];

Javascript: Proper closure syntax and formatting

I am only moderately experienced with JS/jQuery. I am attempting to parse an XML object that I retrieved from IIS, here's some pseudocode that roughly describes my problem:
//accepts an XML Object
function dataFromAjax(object) {
var x; // this is an int used to ID the object
var y;
var z;
var arr = [];
var __data = this;
var xmlObject = object;
function readDataFromXMLObject() {
__data.x = $(xmlObject).find("X").text();
__data.y = $(xmlObject).find("Y").text();
__data.z = $(xmlObject).find("Z").text();
testArr = $(xmlObject).find("TestArrInfo").text().split(",");
if(testArr[0] != null)
__data.arr.push(testArr[0]);
// ...
}
function storeData() {
sessionStorage.setItem(__data.x, JSON.stringify(__data));
}
readDataFromXMLObject();
storeData();
}
In the console it gives me the following error while attempting to parse arr[]:
Uncaught TypeError: Cannot read property 'push' of undefined
When I try manually typing something like sessionStorage.getItem(123) (with and without quotes) it also returns null.
To test the values, I tried both console.log(xmlObject) and console.log(__data.x) for debugging, those worked fine and gave me the XML object and value of x, respectively. Not sure why the array isn't working or why the whole object doesn't save. I'd greatly appreciate any hints.
In this scope you can access to arr directly:
arr.push(testArr[0])
Your this context probably points to window object. window.arr is undefined.
Read about this context in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

got stuck with this set of code in jquery validate

var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.

Categories