I get from Firebase Realtime Database data by task.getResult().getValue()
. It looks like:
{
jyIibta0UWaRF2={Name=Value1, Surname=Value2},
Oy8r5SEYacKKM2={Name=Value3, Surname=Value4}
}
How can I convert it to Array. So I can find an item by its index.
Like:
data[1][1]; //Must return "Surname=Value4"
CodePudding user response:
To convert the object to an array, you could do something like this:
const obj = {
jyIibta0UWaRF2: {Name: "Value1", Surname: "Value2"},
Oy8r5SEYacKKM2: {Name: "Value3", Surname: "Value4"}
}
let data = [];
Object.keys(obj).forEach((key) => {
data.push(["Name=" obj[key].Name, "Surname=" obj[key].Surname]);
});
console.log(data[1][1]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
But since you mention this comes from Firebase Realtime Database, I recommend learning to navigate the DataSnapshot
class from there. Given a snapshot
with the structure you show, you can navigate it with:
for (DataSnapshot child: snapshot.getChildren()) {
Log.d("Firebase", child.getKey()); // "jyIibta0UWaRF2", "Oy8r5SEYacKKM2"
Log.d("Firebsae", child.child("Surname").getValue(String.class); // "Value2", "Value4"
}
This uses the two ways to navigate data in a DataSnapshot
:
- If you don't know the key of what you need, you can loop over all children/properties with
getChildren()
. - If you know the key/name of what you need, you can access it with
child(...)
.
And to retrieve data:
- Call
getValue(...)
with the type of data of the property (aString.class
in this case.