Reputation: 43
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
Reputation: 19515
Assuming
obj
,obj.timetables[2]
(i.e. “second child
”),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