1

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);
});
*/
6
  • How do you determine which object the key you’re searching is on? Will your keys always be numerical? Apr 1, 2018 at 9:27
  • I first find the current time, and then take my starting key as the hour from that timestamp. Apr 1, 2018 at 9:31
  • So, now, starting from this key, I need to find the first object with a non-null value Apr 1, 2018 at 9:32
  • But will it always be on the second object in that array, i.e. .timetables[2]? And again, will your keys always be numerical? Apr 1, 2018 at 9:33
  • Yes. You can assume that its on timetables[2] for this question. Apr 1, 2018 at 9:36

1 Answer 1

1

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

2
  • How do I assign a json file's content to a variable obj? Apr 1, 2018 at 10:16
  • @AjaySubramanian Isn’t that object just data.val() in your ref.once callback? Apr 1, 2018 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.