Querying all maps from an array in a document - javascript

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.

Related

retrieve key names from firebase react-native

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

How to create an array of objects inside a loop, without a key in Javascript

I am just unable to figure out a way of creating, a list of objects, inside an array, and they should not have any index attached to them.
let allConditions = []
for (let i = 0; i < 3; i++) {
allConditions.push({
datasource: 'datasourceName',
column_name: 'columnName',
id:i
})
}
console.log(allConditions)
This gives me a result like:
And this is what I need:
What am I doing wrong ? The console log I am getting in the snippet is what i want, but that's not what you will get if you copy my code and use it in Google chrome's console. Same goes for my code, I get 2 rows with indexes 0 and 1, which is expected as I am using .push method. What else should I do get an array, which can hold many similar objects, but have no key.
UPDATE: To the people answering that indices will always be there, even if I don't use one, I am sending this data to a backend api, and it rejects my request because it does not find an 'array of objects. So I am not sure what I should do.
Arrays will always have indices, although you don't have to use them. Even if you created your array manually outside the loop, it would have indices.
The 2 are equivalent, the keys or array indexes are always there.

Can't print array declared in this.state.arr in react native?

I have an array called this.state.arr, which I added values to in another function in my app.js file. In the render() function I console.log(this.state.arr) the array to show and it shows like this:
[]
0: "a"
1: "b"
2: "c"
length: 3
However, I want to be able to access the individual elements of each array. I've tried this.state.arr[0], or const list = this.state.arr.map((e) => {return e;}); I've also tried some other commands to access the insides of the this.state.arr array.
But none of those worked. I just kept getting null in the console when I tried to access the inner elements of the array. Any help would be greatly appreciated!
Having null get returned for your attempts to access items in this.state.arr is pretty unusual and makes me think that something else is populating or interfering with your array. When you try to access an item at an index your array that doesn't have a value undefined will get returned. null is typically used to indicate a value/property/attribute is intentionally being set to blank.
I'd double check where you are setting / accessing the arr. Posting that part of the code may help.

Javascript - key and value in array

I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));

Name Indexes in Javascript - Array / Object?

I understand that when index names are used to push values in Javascript, they essentially work like objects. But what I don't understand is the following behaviour -
person = [];
person[0] = "Someone";
person["test"] = "SomeoneElse"
Inputting person on the console prints ["Someone"] and I could see no information about person.test.
person.test does print SomeoneElse. However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
Curious to check if this makes sense, I tried to create a structure like this one -
var experiment = ["Someone1", test1: "SomeoneElse1"]
and what I get is
Uncaught SyntaxError: Unexpected token
What am I missing?
Thanks in advance!
Typing person on the console prints ["Someone"].
Array.prototype.toString formats this output, and it only considers the "array values" of itself without other properties.
However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
console.log outputs other information about the object, including own properties.
Uncaught SyntaxError: Unexpected token
Because that is bogus syntax; the array literal syntax doesn't allow keys, because array values aren't supposed to have keys. Arrays are a numerically indexed list of values. Merely by the fact that under the hood those lists are implemented using objects (because everything in Javascript is an object of some kind or another) are you able to set "non numeric keys" on the array. That doesn't mean you're using the array correctly though.
Also see Are JavaScript Array elements nothing more than Array object properties?
This is because an array in JavaScript is also an object itself, and objects can have properties. So it is perfectly valid to have an array with elements, but also have properties set on the array object.
The second example doesn't work because the [...,...,...] syntax is specifically for instantiating an array and its elements.
typing person in console is like having an alert(person); or passing its value to a variable or element, so it is more like you want to get the first set of readable values. That is the reason why it is showing you the values inside, you can try adding person[1] = *something;*, then it will display someone, something
console.log(person) - it displays all the items inside an object. It is more like informing you of what is inside, like a text visualizer in your IDE
var experiment = ["Someone1", test1: "SomeoneElse1"] - it will absolutely throw an exception there is no such format like this on initializing values, at least it is expecting an array format like var experiment = ["Someone1", "SomeoneElse1"]

Categories