最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Store data in Firebase as JSON object - Stack Overflow

programmeradmin1浏览0评论

So I am working on a small web app and I am using Firebase for the back-end. It's a small chat application and I am trying to store the messages of a person in the following form:

{ "John" : {0: "hello",1:"how are you?".2:"what are you doing?" }}

I am storing the person's name in a variable called my_name. My Firebase reference is called ref. Say I set my_name as,

var my_name = "John";

and then do

ref.set({my_name : {0:"Hello"}});

It stores the data as

{my_name : {0:"Hello"}}

instead of

{"John" : {0:"Hello"}}

How can I store it so that it uses the assigned value of my_var ?

So I am working on a small web app and I am using Firebase for the back-end. It's a small chat application and I am trying to store the messages of a person in the following form:

{ "John" : {0: "hello",1:"how are you?".2:"what are you doing?" }}

I am storing the person's name in a variable called my_name. My Firebase reference is called ref. Say I set my_name as,

var my_name = "John";

and then do

ref.set({my_name : {0:"Hello"}});

It stores the data as

{my_name : {0:"Hello"}}

instead of

{"John" : {0:"Hello"}}

How can I store it so that it uses the assigned value of my_var ?

Share asked Mar 21, 2016 at 17:59 prithajnathprithajnath 2,11515 silver badges17 bronze badges 1
  • Why is the chat data being saved as an array? That's probably going to cause issues later. When storing chat data like this, a better option may be to push() to generate node names and store the messages as a key:value pair within each node. Doing it like that will enable you to store who the message is from and to as well as timestamp, perform queries and other details. Also, you have a period in your example (.2) instead of a ma. – Jay Commented Mar 22, 2016 at 14:48
Add a ment  | 

3 Answers 3

Reset to default 3

Try putting brackets around your property name like so:

var my_name = 'John';

ref.set({
  [my_name]: { 0: "Hello" }
});

Create a JS object like this

var obj = {};
obj[my_name] = "{ 0: "Hello" }";

then save this to Firebase

ref.set(obj);

Check your {} in set.

var car = {type:"Fiat", model:"500", color:"white"};

        function writeData() {
            firebase.database().ref('cars/'+ dateToInsert).set(
                car
            );

That save:
type:"Fiat"
model:"500"
color:"white"

        function writeData() {
            firebase.database().ref('cars/'+ dateToInsert).set({
                car
            });

That save:

car:
- type:"Fiat"
- model:"500"
- color:"white"

发布评论

评论列表(0)

  1. 暂无评论