So I'm trying to save an object via the chrome.storage API. The relevant code is:
var images = null;
var storage = chrome.storage.sync;
var key = "key";
images = getImages(source);
alert(images.length); // returns 4
storage.set({key: images});
storage.get("key", function(result) {
alert(result.length); // returns undefined
});
I'm tested that immediately after the getImages() function, images is a wrapped set JQuery object with a length of 4. However, when I try to access images.length via the storage.get callback, the result is undefined.
Could someone help identify the error in how I am storing and/or retrieving this JQuery object?
Update 1:
Thank you all for your help. As clarification for the use case, I am using chrome.storage instead of localStorage because I plan to pass extension info to another script.
Fortunately, TranQ/Xan's solution has enabled me to access the array via the storage.get call.
I'm still experiencing issues working with the wrapped set JQuery object stored in the array but I'll post a separate question since the current solution encapsulates broader use cases.
TranQ's comment is on point.
Presumably, images is an array. You store that array under the "key" key.
When you execute the get() function, it returns an object populated with all key-value pairs you asked, even if you only ask for one key.
So, result is an object {key : [/* something */]}. Objects do not have a length property, and you get undefined
You need to use result.key (or result["key"]) to access your array.
Related
I'm trying to turn an array in which every element is an array containing the key, and the value(like entries), I'm trying to convert it back to an object element by the help of the method Object.fromEntries(array) but there seem to be a problem.
This is the error I get: TypeError: Object.fromEntries requires the first iterable parameter yields objects
Here's how I use the method:
const saved = JSON.parse(Object.fromEntries(localStorage.getItem(key)))
The local storage value it should retrieve:
[["$$typeof",null],["type",null],["key",null],["ref",null],["props",{"data":"a data containing collections of objects(fetched from an API)"}]
Since it might be helpful, what I'm trying to do is to store a react component(yes, I work on ReactJS) to local storage and get it back when necessary.
If you don't think that this portion of code is not the reason why this issue appears, please do let me know.
I am working with AbsoluteOrientationSensor
I have an object that contains the values of the accelerometer of the phone.
The values that I need are nested inside an Symbol in the Object.
How do I access those values?
The Object Name is "message".
I have already tried this
console.log(message.__sensor__.quaternion);
But I am getting the result as "undefined".
I have never worked with the Symbol data type in JavaScript before.
The Values that I want to access are the quaternion values
This is the screenshot of the Object Structure -
Thank you for your help.
From the documentation:
Properties
OrientationSensor.quaternion: Returns a four element Array whose elements contain the components of the unit quaternion representing the device's orientation.
So:
console.log(message.quaternion);
You can also see in the screenshot that the object itself has a getter quaternion.
I have never worked with the Symbol data type in JavaScript before.
Symbols are used for various reasons as property names, but if they are used, it almost always means that you, as a consumer of the API, are not supposed to access that value directly. Instead you should use the "public" API the object provides to access this data, such as in this case.
function GetSymbol(object, name) {
const string = `Symbol(${name})`
return Object.getOwnPropertySymbols(object).find(symbol => symbol.toString() === string)
}
const __sensor__ = GetSymbol(message, "__sensor__")
console.log(message[__sensor__])
At the moment I am storing a few objects in Firebase. After successfully retrieving the items from Firebase and storing them in a firebaseArray, I want to further thin out the unwanted elements by deleting the elements in the firebaseArray that do not have the desired property. Consider my code at the moment, that does not do as wanted, however there are no errors in the console:
var querylatestPosts = firebase.database().ref("Topics");
$scope.latestPosts = $firebaseArray(querylatestPosts);
console.log($scope.latestPosts) ;
$scope.latestPosts.forEach(function(el) {
if ($scope.checkWorldview(el) == false) {
delete $scope.latestPosts.el ;
}
});
(Note I am unable to log 'el' in the console, nor does the forEach seem to execute, as I can log nothing in the function in the console)
The 'checkWorldview' function behaves as expected when elements are fed in different instances and returns false if the required property is not present in the element under consideration. Thus if the function returns false, I want to delete the specific element in $scope.latestPosts that does not contain the wanted property.
I hope this is clear, thank you in advance for any help you can offer!
The way you are using the $firebaseArray isn't recommended by the docs (see here), which state that $firebaseArray is read only and should not be manipulated.
So you have a few options:
Instead of filtering the array on the client-side, you should modify the query you're using to retrieve data from Firebase to only get elements that have the desired property (ex: use 'equalTo' in the query)
OR
Don't use a $firebaseArray because you're not using it in the way it was intended. Use a regular, good ol' fashion JavaScript array instead.
** Also, just a general comment: don't delete elements from an array as you loop through it as this is generally bad practice (we don't expect arrays to have elements added/removed while we loop through them). Instead, use Array.filter.
Say I have an object store, which was created like this:
IDBDatabase.createObjectStore(Name, {autoIncrement: true });
Now, say I retrieve an object from that object store using an index to look it up.
Is there a way that I can retrieve the out-of-line key associated with the object so I can modify/delete it with IDBObjectstore.put() / IDBObjectstore.delete(), or am I stuck iterating over the object store with a cursor (comparing based on some arbitrary property) and using cursor.update() / cursor.delete()?
Initially I would think not, because the point of having specific keys is that two identical objects might reside in the object store, so the browser can't know what object to give you when its provided with only the object itself. Presumably though, since I retrieved it with an index in the first place, there may be some way to utilize the index to retrieve the out-of-line key that's associated with the object I am working with.
When data is inserted into datastore then the event object returned contains the information about the key used for inserting data. It can be retrieved using event.target.result. You can collect the information at that time.
Whether in-line-keys or out-of-line keys, you can get it same way.
var transaction = DB_HANDLER.transaction([tableName], "readwrite");
var objectStore = transaction.objectStore(tableName);
var request = objectStore.add(data);
request.onsuccess = function(event) {
console.log("Key used for inserting data = " + event.target.result);
};
You have to keep the out-of-line key generated when you put. It is in the success request event result.
I have an IndexedDB of changes. I add an item like this, and then log the result to check the key has been created successfully:
_this._idb.add('steps', step).done(function (items) {
var item = items[0];
_logger.log("ADDED STEP", { id: item.__id__, step: item }, "CT");
});
The output from this is as expected:
...as you can see, the id has been added to the object when it is stored.
However, when I query the db to getback a list of objects, using this code:
this._idb.steps.query('timestamp').bound(start, end).execute().done(function (results) {
_logger.log("Results", results, "CT");
}
I don't get the id as part of the object that is returned:
... and the lack of id makes updating and deleting impossible.
How can I get the id of the item when I query indexed db using db.js - or am I approaching this in the wrong way, and is there something else I should be doing?
(Note: I'm using TypeScript to compile the JS, but I don't think that's especially relevant to this question)
This is expected behaviour, you're only going to get the __id__ property if you don't define a keyPath in your db schema.
Because there's no keyPath defined the value is not associated with it in indexeddb, it's only added to the resulting object after it has been added, because at that point in time we know the auto-incremented value that IndexedDB has assigned to it.
Since the value isn't really part of the object I don't have any way to assign it to the object when it comes out during a query, maybe I could use the position in the array but that's more likely to be wrong than right.
If you want the ID to be persisted against the object then you need to define a keyPath as part of the object store schema and the property will be added to the resulting object and available and it will be on the object returned from a query.
Disclaimer - I wrote db.js
Looking at the source, __id__ is only defined when your keyPath is null in the add() method. From what I'm seeing, you'll never see this in a query() response.
In IDB null keyPaths are allowed only when using auto-incrementing ("out-of-line") keys. So if you're getting the object back, it should have an auto-incrementing key on it or some other keyPath.
The __ prefix in JavaScript usually means the developer intended it to be a "private" property. I'm guessing this is for internal use and you shouldn't be counting on this in your application code.
Consider using explicit, so-called "in-line" keys on your object store.
The goal of db.js is easy and simple to use. Your is advanced use case.