Andy
Andy

Reputation: 51

getting the key/pair values out of an object that in an object

Objects thats returned:

Objects thats returned

ref.orderByChild('name').once('value').then(function(snapshot){
    var results = snapshot.val();

When i log results the image is what i get, Ive been trying to access the value of 'active' for each of the three objects, phishing, information and techniques.

This is my first JS application sorry if its an easy one but couldn't find an answer else where that worked.

Upvotes: 2

Views: 331

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599776

There are two (common) ways to do this: the Firebase way and the regular JavaScript way.

the Firebase way

Since it seems you're returning a list of nodes, I'll start with the Firebase way.

ref.orderByChild('name').once('value').then(function(snapshot){
    var actives = {};
    snapshot.forEach(function(childSnapshot) {
        var result = childSnapshot.val();
        var key = result.key;
        var active = result.active;
        actives[key] = active;
    }
    console.log(actives);
}

So we're using Firebase's Snapshot.forEach() method here to loop over the child nodes.

the regular JavaScript way

Alternatively you can get the value of the entire snapshot as you already do and use plain old JavaScript to get the result you need. Jatin's answer shows one way to do that, but here's another:

ref.orderByChild('name').once('value').then(function(snapshot){
    var results = snapshot.val();
    var keys = Object.keys(results); // ["information", "phishing", "techniques"]
    var actives = {};
    keys.forEach(function(key) {
        actives[key] = results[key].active;
    });
    console.log(actives);
}

So in this case we're using Object.keys() to get the child node names and then loop over that array with JavaScript's Array.forEach().

Upvotes: 2

Jatin patil
Jatin patil

Reputation: 4288

var snapshot = {
  "information" : {
    "active" : "y",
    "name" : "information"
  },
  "phishing" : {
    "active" : "z",
    "name" : "phishing"
  },
  "techniques" : {
    "active" : "x",
    "name" : "techniques"
  },
};

console.log(snapshot.information.active);
console.log(snapshot.phishing.active);
console.log(snapshot.techniques.active);

Upvotes: 1

Related Questions