retrieve key names from firebase react-native - javascript

I have a little problem regarding Firebase and retrieving names of parent keys. Like in this example I want to get the names of the keys, not their values:
Pls have a look in my db how it looks now, its exactly the same like in the JS sandbox:
When I try to implement this in my react-native project, basicly with plain JS in this part, it looks like this:
const sendletter = () => {
console.log("letter send");
firebase.database().
refFromURL("https://SOMEDATABASE.firebaseio.com/numers").
once("value").then(snapshot => {
for(key in snapshot){
console.log(key)
}
})
};
The problem I just face now it the outcome of the console in my IDE:
null letter send node_ ref_ index_ val exportVal toJSON exists child
hasChild getPriority forEach hasChildren key numChildren getRef ref
I tried to provide you as many pictures so the problem gets really clear and also my goal I want to archieve, to get the key names itself, NOT the values the keys are linked to. Any help would be appriciated!

You want to use snapshot.val() instead of just the DataSnapshot object
for(key in snapshot.val()){
console.log(key);
}
When you are looping through just the snapshot variable, you are looking at all the keys in that DataSnapshot that is returned from firebase and not your actual data. If you check out Firebase docs, you'll see what the DataSnapshot object represents and how to actually get your data from the database FROM their DataSnapshot object that is returned: https://firebase.google.com/docs/reference/node/firebase.database.DataSnapshot
If you look close enough you can see that all the methods and values that this DataSnapshot object contains is actually what was being printed in your console all along

Related

localStorage into HTML

How would I go on to get the information in the same format as it was saved?
Saved as, example:
document.querySelector('.btn').addEventListener('click', function(event){
const store = {
ci: document.querySelector('.a').innerHTML,
};
localStorage.setItem(store.city, JSON.stringify(store))
This is my code, the storage got different keys:
function myFunction(){
document.querySelector('.a').innerHTML = JSON.stringify(localStorage.getItem(i))}
Although it was not clear to me what is your expectation or expected behavior. But I will try to give an answer with the limited data.
You can get all the keys in localStorage by Object.keys method. And then iterate over the keys and JSON.parse all the localStorage[key].
Object.keys(localStorage).map(key => console.log(localStorage[key]))
That should solve your problem of getting the objects from localStorage.
According to the docs, Storage items can only store data of type DOMString. Converting other data types into a string using the JSON.stringify function is a valid idea!
You only need to reverse this change when reading the data:
function setObjectItem(key, item){
return localStorage.setItem(key, JSON.stringify(item));
}
function getObjectItem(key){
return JSON.parse(localStorage.getItem(key));
}
However, some data types can not be converted into a JSON string. For example, you cannot use this method to store DOM elements.

Querying all maps from an array in a document

I'm trying to query all data from an array in Firestore, but the certain array is made of objects. This is what my DB looks like:
https://imgur.com/a/4n1A2mb
You guys have any idea how I should do it?
This is the code I'm trying to achieve my goal with:
sawroomDB.collection("reservationsSecure").doc(todaysDate.getFullYear().toString()).get().then(doc => {
tableAllReservationsBody.innerHTML = doc.data().allReservations;
console.log(doc.data().allReservations)
})
The output I'm getting printed is just "[object Object],[object Object]" and in the console I can see and browse the arrays
What I need is to see the whole information from the objects, just by calling the array.
Thanks!
doc.data().allReservations is going to be an array of objects, as you can see from the console output. From what we can see in the screenshot, those objects contain at least one property called booking. If you want reach into the first object and get the value of the booking property:
const allReservations = doc.data().allReservations
const r1 = allReservations[0]
console.log(r1)
const booking = r1.booking
Of course, you might want to iterate the allReservations array instead of blindly indexing into it. But the point here is that each object just has that properties that you see in the console. You'll be able to see better when you log each object individually as above, rather than trying to log the entire array, which might compress down the contents of each object from your view.

Get value of object inside of array which is inside an object itself

I have a quick question which I seem to be tripped up on.
I have a data structure like so:
data: {
accounts: [{
info: false
}]
}
Is there a "fancy" React way for me to get the value of the boolean associated with the info key?
I can of course retrieve the value with using map or find, but it always ends up being somewhat convoluted or involved code.
If I do something like
const { accounts } = data;
const customer = accounts.map(a => a.info);
The value for customer always ends up coming back as [false] instead of just false, which is really confusing me, because I am not sure why it would come back inside of an array, where it is not an array to begin with, and it is being mapped out of an array (accounts).
I had the same result when using forEach and find.
Is there something I'm missing? There has to be a quick Reactive one-liner to get the boolean value I'm looking for, and set it to a variable.
Anyone...?
data.accounts[0].info
or
Using underscore.js
_.first(data.accounts).info

JSON object recieved from api property returns undefined

For the project that I am working on, I am using the Shopify API which allows you to retrieve products and other information from your store to be retrieved in the format of a JSON object. I was able to successfully get the JSON object from the API, however when I try to access a property of the JSON object, it returns undefined. I have looked at a couple of articles that I will refrence below, but the problem for those users were things such as needing to use:
JSON.parse()
for a JSON object enclosed by strings which is not my probelem, I have tried a few other work arounds as well but with no luck, I originally thought that the problem was that my code needed to use an "Async/Await" function in order to wait for a response from the API, but I then realized that wouldn't make sense considering I can recieve the whole JSON object itself with no problems.
When I use:
request.get(url, {headers})
.then( result => {
console.log(result); // Only accessing object itself
});
I recieve the JSON object response correctly with no error like this:
{"products":[{"title":"Test Product 1","body_html":"This is a product that is being tested for retrieval!",
"product_type":"","created_at":"2018-08-21T17:49:07-07:00","handle":"test-product-1","updated_at":"2018-08-21T17:49:07-07:00","published_at":"2018-08-21T17:48:19-07:00","template_suffix":null,"tags":"",
"published_scope":"web","variants":[{"title":"Default Title","price":"5.00","sku":"","position":1,"inventory_policy":"deny",
"compare_at_price":null,"fulfillment_service":"manual","inventory_management":null,"option1":"Default Title","option2":null,"option3":null,
"created_at":"2018-08-21T17:49:07-07:00","updated_at":"2018-08-21T17:49:07-07:00","taxable":true,"barcode":"",
"grams":99790,"image_id":null,"inventory_quantity":1,"weight":220.0,"weight_unit":"lb","old_inventory_quantity":1,
"requires_shipping":true,}],"options":[{"name":"Title","position":1,"values":["Default Title"]}],"images":[],"image":null}]}
However when I use this, the JSON object property returns undefined:
request.get(url, {headers})
.then( result => {
console.log(result.products[0]); // Accessing the first item in JSON "products" array
});
Articles I have already checked out:
cannot access json object property returns undefined
JSON object returns undefined value
JSON objects returns undefined
Would anyone be able to explain my error or why this is happening? I am more than happy to edit my question to include any code/information that might be helpful.
Thanks in advance,
Michael
try this:
console.log("data:", JSON.stringify(result.products[0], null, 2));
console.log to print the result to your console. Use Chrome and developer tools and you will see a console option - excellent for debugging.
JSON.stringify turns the JSON data into something you can see and read. You can convert the data and then split as you need this way too.
OK, a second answer. I can't check this, as I don't have your JSON data, however, I would try something that would likely resemble this...
data.Items[0].field
if the data is not correctly formatted then take the stringify approach and split it out. Otherwise, consider this:
products":[{"title":"Test Product 1"
variable = products[0].title;
I would tend to use a function to pull all the data out in one shot.
function Getv(data){ global.myApp.v = JSON.stringify(data, null, 2); }
then I might run this...
Getv(data.Items[0]); let splitData = global.myApp.v.split('\"'); let vCount= splitData.length;
if the object returns like this it wouldn't work because it's missing a colon after "products" identifier. like Luca said it's not a valid JSON response
Try this:
var resultJson = JSON.parse(result);
console.log(resultJson.products[0].varname);

How to get the main object of a firebase database?

Here's a quite simple question but I have not been able to find an answer anywhere about this, so hopefully I can get the answer here.
I want to iterate through the keys in my database using:
for (var key in X) {
//X is the main object I need
}
However, in order to do this I need the actual object of the database, not the reference to the database. Because when I iterate over the reference I get a lot of nonsense properties. So how do I get the object containing all the keys that I add personally? Hopefully my question makes sense.
This can be done this way:
var value;
myDataRef.on('value', function(snapshot) {
value = snapshot.val();
})

Categories