0

I have this collection in firebase realtime database:

students:

{
  "Mike": {
    "Time 2022-08-22 09:04:57": {
      "Courses": [
        "Maths",
        "Chemistry",
        "Science"
      ]
    },
    "Time 2022-08-15 09:05:58": {
      "Courses": [
        "Physics",
        "Geography",
        "Literature"
      ]
    },
    "Time 2022-08-15 09:06:59": {
      "Courses": [
        "Computer Science",
        "Biology",
        "Chemistry"
      ]
    }
  },
  "John": {
    "Time 2022-08-22 10:04:57": {
      "Courses": [
        "Maths",
        "Chemistry",
        "Science"
      ]
    },
    "Time 2022-08-15 10:05:58": {
      "Courses": [
        "Physics",
        "Geography",
        "Literature"
      ]
    },
    "Time 2022-08-15 10:06:59": {
      "Data": [
        "Computer Science",
        "Biology",
        "Chemistry"
      ]
    },
    "Time 2022-08-15 10:07:59": {
      "Courses": [
        "Computer Science",
        "Biology",
        "Physics"
      ]
    }
  },
  "Steve": {
    "Time 2022-08-22 11:01:57": {
      "Courses": [
        "Maths",
        "Chemistry",
        "Science"
      ]
    }
  }
}

Now here I want to get the name of students only instead of retrieving complete object data.

Expected Response:

["Mike", "John", "Steve"]

What I tried so far is:

<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
var config = {};

firebase.initializeApp(config);

var records = [];

var ref = firebase.database().ref("students")

ref.on('value', function(snapshot) {
    
    var records = snapshot.val();
    
    for(var key in records) {

        records.push({
            user: key
        });             
    }    
});
</script>

In my case it provides the correct response but with basd approach, currently it is traversing all the data.

I need firebase to give me names of users only.

StormTrooper
  • 1,731
  • 4
  • 23
  • 37

1 Answers1

0

To get only the keys into your array:

ref.on('value', function(snapshot) {
    var records = [];
    snapshot.forEach((child) => {
        records.push(child.key);
    }
    console.log(records);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807