Reputation: 53
I have a real-time firebase database with a structure like this:
-- places
-- user1 uid
-- name:
-- latitude:
-- longitude:
-- user2 uid
-- name:
-- latitude:
-- longitude:
When fetching the data from firebase, I wanted to store it like this
-- user1 name
-- latitude
-- longitude
-- user2 name
-- latitude
-- longitude
Currently I have this code structure which loops through the data, but I am stuck on getting each data and store it as shown above.
constructor(props) {
super(props);
this.state = {
places: []
};
}
componentDidMount() {
const ref = firebase.database().ref('places/');
ref.once('value', (snapshot) => {
snapshot.forEach(snapshotchild => {
snapshotchild.forEach(data => {
})
})
});
}
Upvotes: 1
Views: 2106
Reputation: 3856
Looking at the data table, I am assuming you are getting the data somewhat like this
const places = {
user1Uid: {
name: 'av',
latitude: '1000',
longitude: '1000'
},
user2Uid: {
name: 'we',
latitude: '1000',
longitude: '1000'
}
}
If this is how it it is, you can manipulate the data using Array.forEach
, for in
or even with Array.reduce
,
For example to
const obj = {};
Object.keys(places).forEach(item => {
obj[places[item].name] = {
latitude: places[item].latitude,
longitude: places[item].longitude
}
});
console.log(obj);
or if you wanna use reduce,
const newObj = Object.keys(places).reduce((accumulator, item) => Object.assign({
[places[item].name]: {
latitude: places[item].latitude,
longitude: places[item].longitude
}
}, accumulator), {});
console.log(newObj);
You will get an object in console like
{
"we": {
"latitude": "1000",
"longitude": "1000"
},
"av": {
"latitude": "1000",
"longitude": "1000"
}
}
If you wanna learn more about Reduce here's a link
Happy coding :)
Upvotes: 1