How to get the main object of a firebase database? - javascript

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();
})

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

Push variable outside nested functions

I'm not sure why this isn't working so if anyone can help that would be great. I have nested functions and I wand to push the value returned by the firebase query and re use it in another firebase query, and then again, in a loop. Its essentially a poor man's infinite scroll. Nonetheless, I cannot get the value of the "arr" variable into the "numWanted" array outside so I can use it again in the next loop. What can I do to achieve the desired result?
Also, I have have beed trying to make the inner variables global, and push them out to another variable but that doesn't seem to work. Possible that I am just doing it wrong?
Thanks in advance..
$scope.loadMoreData = function() {
var numWanted = [];
console.log(numWanted);
firebase
.database()
.ref('products')
.orderByChild('rank')
.startAt(0)
.endAt(numWanted)
.limitToLast(3)
.once('value', function(products) {
products.forEach(function(product) {
var product = {
rank: product.val().rank
};
arr = product.rank;
});
numWanted.push(arr);
console.log(numWanted);
});
};
P.S. I realize this code doesn't actually work as you cannot use an array in a firebase query. My plan is to extract the number I need once the array has been populated.
You have a conflict with your parameter named product and a local variable named product. You need to rename one of those.

Getting Key name of an Object item

Before marking this as a duplicate, i've spent a lot of time looking through similar question and most of the answers did not solves my situation.
i have a huge list of items as objects by IDs. like this, in a Map (userDB)
{
"15321":{name:"name1",status:"status1"},modules:{...},
"15322":{name:"name1",status:"status1"},modules:{...},
"15323":{name:"name1",status:"status1"},modules:{...}
}
now i need to make an operation in which i need all these IDs, in that case, the key names of every item on it. i need to get these "15321","15322" etc.
more specifically i wanted something that i could fetch in something like
userDB.forEach( u => {
//something here to get u's key
})
i've tried Object.keys(), but it will return a list of IDs as an object
{"15321","15322"...} in which i still cant grab the ID string
i've tried for (i in Object.keys(userDB)) too, no successs
i double-checked for silly syntax errors and everything of the sort.
Things that will be nice to get in mind to answer this:
dont try to show me a new way of storing stuff, it is already stored so you will not be of help
the result SHOULD be the ID as a string, the name of the key.
dont ask "why i want to make this". just answer and dont try to change this scenario. because this is what i've seen in most of the other similar questions and it is what makes me walk in circles every time.
TL;DR. i just want to get the parent key names of the object im currently processing
Object.keys(obj) will return an array.
But in your data there is another key modules except IDs.
So you can use this :
var keys = Object.keys(data);
keys.pop();
console.log(keys); // ["15321", "15322", "15323" ...]
You might be confused. Object.keys(obj) returns an array. In your case it looks like this: ["15321", "15322", "15323"]. You could iterate through that array like so and you'll have both the key and the object and you'll be able to do with them whatever you want. Below is a for loop that attaches the key to the object as a key named 'key'.
var keys = Object.keys(myObject);
for(var i = 0; i < keys.length; i++){
var key = keys[i]; // this is your key
var obj = myObject[key]; // this is the key's value
obj.key = key;
}
EDIT
In javascript an Array is also an object, but the 'keys' so to speak are usually numbers instead of strings. So an array that looks like this:
["Hello", "there"] is essentially represented like this: { 0 : "Hello", 1 : "there" }
When using for-in on an array, it'll loop through the keys, but those keys will be 0, 1, 2... instead of the items themselves.

Get object property value

I have an object that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.

How to access fields in JSON object by index

I know this isn't the best way to do it, but I have no other choice :(
I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:
(for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
(Soruce : Loop through Json object).
However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.
As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?
A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:
var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
alert(object[keysbyindex[i]]);
But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop
var counter = 0; // if you need it
for (var key in object) {
alert(object[key])
counter++;
}
? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.
Based on Bergis anserwer this is my solution:
var keysbyindex = Object.keys(this);
alert(this[keysbyindex[index]]);
return this[keysbyindex[index] || ""];
However, I think (not tested) it's extremly bad regaring performace and shouldn't be used! But desperate times require desperate measures.....
I don't think you can actually achieve this without creating your own parsing of JSON. You're writing that you want to go trough a JSON-object, but what you're actually trying to do is go trough a plain old Javascript object. Json is simply a string-representation used to transfer/store said object, and in here lies the main problem: the parser that transforms the string into an actual object (ie. the browser in most cases) can chose to ignore the order it finds the properties if it want to. Also, different browsers might have different approaches to parsing JSON for all you know. If they simply use a hash-map for the object that it's simple to loop through it, but the order won't be dependent on the order of the keys in the file, but rather the keys themselves.
For example, if you have the json {"b":"b","a":"a"} and do the for in loop, under some implementations you might end up with a comming first, and in others you might end up with b.
var jsn = {keyName: 'key value result come here...'};
var arr = jsn ? $.map(jsn, function (el) { return el }) : [0];
console.log(arr[0])
$('.result').text(arr[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="result"></span>

Categories