0

During storing an object to my firebase, I am expecting the structure as image below, but what I get was a generated running number as a key. This is my code to store an object to firebase

var location = [];
location.push({
  ms_jhr_1 : {
    name: value
  },
  ...
});
const a = firebase.database().ref('Food/'+id);
a.set(location);

Expected structure

How do I keep my structure without generate the running number?

1
  • 2
    Firebase doesn't store arrays, only maps. The key names need to be unique. I would restructure location = {} and use Object.assign(location, newData). If you have to have an array, then you are going to need to use Array.reduce to create a map to send to firebase. Commented Aug 27, 2018 at 11:55

1 Answer 1

3

The problem is you are using an array to store your data and then setting that array in firebase. To get the expected result you have to modify your code a little bit.

Here use this and remove other code

const a = firebase.database().ref('Food/'+id);
a.set(ms_jhr_1);

So you just need to pass the object you want to store under that id and not the whole array.

Note:- If you want to store multiple entries under one id then you have to push all those entries in an Object and not in array.

So it will look something like this

var location = {};

Now use for loop to insert all your data into this object (Remember, you are adding objects inside an object). You don't need array. Because in firebase data is stored in JSON tree format.

Hope it helps.

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

3 Comments

var location = {}; still generate a key number if i use location.push.. to push multiple object inside it.
Don't use .push method, it is used for array. Just use for loop to insert data into location object. You can use for in loop to add object inside an object.
Great answer @PradhumnSharma! Firebase Database indeed stores arrays as objects with keys 0, 1, etc. It sounds like ggDeGreat wants an object/set instead of an array, so getting rid of the array (and calls to push()) is the way to go. Another way to initialize the location object is: location.ms_jhr_1 = { name: value } or location["ms_jhr_1"] = { name: value }.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.