Ajay Subramanian
Ajay Subramanian

Reputation: 43

Obtaining the first non-null value after a particular key from a firebase database

I have a firebase database that looks something like this:

{
    "timetables": [null,{
      //first child
    },{
      //second child
      "8": "null",
      "9": null,
      "10": "sleep"
    } ]
}

How do I get the first non-null value after a particular key (say, "8" in the second child) ?

"9" has a null value. So, I should get the value corresponding to "10", "sleep"

How to modify my code in order to do this?

let loc = "timetables/" + datetime.getDay(); // datetime.getDay() returns a number from 0-6 which corresponds to one of the children.

var ref = db.ref(loc); // positioning reference at the appropriate child

I thought of using the below function, but wasn't able to come up with how to use it exactly:

ref.once("value",function(data) {
  app.tell(REPORT_MESSAGE + data.val() + ' at ' + data.key);
});
*/

Upvotes: 1

Views: 155

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19515

Assuming

  1. the object shown in your first snippet is assigned to some variable obj,
  2. the keys you’re looking for are always on the object obj.timetables[2] (i.e. “second child”),
  3. those keys will always be numerical, and
  4. the “particular key” from which you’re searching is assigned to some variable fromKey,

you can use Object.assign with [] and obj.timetables[2] as arguments in order to transform the object to an array, which will be far easier to work with, then slice to search from a certain key, then just find the first non-null value:

const result = Object.assign([], obj).slice(fromKey + 1).find((value) => value !== null);

console.log(result); // "sleep"

So, for example:

const obj = {
    "8": "null",
    "9": null,
    "10": "sleep"
  },
  fromKey = 8;

console.log(Object.assign([], obj).slice(fromKey + 1).find((value) => value !== null));

Upvotes: 1

Related Questions