1

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 => { }) }) }); } 
3
  • so your uid ( id) will be name? Commented Mar 2, 2019 at 4:50
  • I didnt use firebase in react-native, but i think it returns a promise. Commented Mar 2, 2019 at 5:28
  • Can you show what you are getting in data? Do a console.log(data); Commented Mar 2, 2019 at 5:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.