I am working on this google auth chat website everything has goon really smooth everything is basically done but the last thing that is to get the messages from a json database i can send messages to the json database but i cant get the array from the object here is my code:
index.js:
socket.on('load', () => {
for (let i in data) {
socket.emit('add message', data[i]);
}
});
main.js(html file):
socket.emit('load');
socket.on('add message', (text) => {
let list = document.getElementById('list');
let li = document.createElement('li');
li.textContent = text;
list.appendChild(li)
});
A traditional json response from the node json DB is as follows:
data = {
test: {
data1 : {
messages : ['test','array']
},
data2 : 5
}
}
From here, getting that messages array is simply to do this:
data.test.data1.messages
Example:
Related
So, I am trying to grab the data from the GET fetch that I used.
const BASE_URL = "http://localhost:3000/quotes"
document.addEventListener('DOMContentLoaded', function() {
randomButton();
createButton();
loadQuotes();
});
const loadQuotes = function() {
fetch(BASE_URL)
.then(res => res.json())
.then(results => {
results.data.forEach(json => json.attributes.sentence)
});
}
function addQuote(quote) {
let ul = document.querySelector('#quote-display');
let li = document.createElement('li');
li.innerText = quote;
ul.appendChild(li);
}
When I wrap a console.log around json.attributes.sentence or use the addQuote(json.attributes.sentence) function like so. I definitely get the out put in the console.log/in the ul/li tags. I also ran a typeof on the json.attributes.sentence and it shows it's outputting strings.
However, I would like to add that data to an array to access later from other methods.
I tried creating a global variable that was an empty array and push the json data attribute strings to the array but didn't work. Ideas?
Thanks in advance.
btw the JSON looks like this
{
data: [
{
id: "1",
type: "quote",
attributes: {
sentence: "Here's looking at you, kid."
}
}
]
}
I have a file named hastanelistesi.json.In this file, I want to access the "hastaneAdi" and display the select-option menu.But I always get the error. I get the json file from mssql. However, I've had more than one query with node.js, so I applied this path.
{
"recordsets": [
[{
"hastaneAdi": "ACADEMİC HOSPİTAL"
},
{
"hastaneAdi": "ACIBADEM BAKIRKÖY HASTANESİ"
},
{
"hastaneAdi": "ACIBADEM KOZYATAĞI HASTANESİ"
}
]
}
//index.js
var fs = require("fs");
var liste = [];
var result;
var rawdata = fs.readFileSync('data.json');
var data = JSON.parse(rawdata);
var grouped_data = data.recordsets.map(function (item) {
return item.hastaneAdi;
});
console.log(grouped_data);
//jade page
td
select#hastaneismi.custom-select(name='hastaneismi')
option(selected='') Seçiniz....
-for item in grouped_data
option=item.hastaneAdi
td
button.btn.btn-light(type='submit', value='submit')
img(style='height: 24px ; width: 24px', src='/images/kaydet.svg')
//and error
Cannot read property 'length' of undefined
Assuming your json data is in a file (for example, data.json) saved in the same script's folder:
const fs = require('fs');
// read data
let rawdata = fs.readFileSync('data.json');
// parse data
let data = JSON.parse(rawdata);
// map data
let grouped_data = data.recordsets.map((item) => { return item.hastaneAdi; })
console.log( grouped_data );
Demo: https://repl.it/repls/StableHorribleWrapper
UPDATE
Assuming you correctly pass grouped_data to jade template, this should work:
select#hastaneismi.custom-select(name='hastaneismi')
option(selected='') Seçiniz....
-for item in grouped_data
option=item
Firebase example:
Users:
User1
A
123
234
345
B
C
Above is the firebase data.
I wanted to call all the data under User1, A. Which means "123", "234", "345" should be the output for my table. I also wanted to display them to be displayed in a table I have in my html file using javascript. Can anyone advise? I am new to firebase and am confused with the other guides online.
Should I create a table using javascript or keep my table at html file?
Thank you for advise and help.
For Real Time Database try this:
firebase.database().ref('/User1/A').once('value').then(function(snapshot) {
let items = snapshot.val();
items.forEach( (v) => writeData(v) );
});
const writeData = (value) => {
let el = document.querySelector('p');
el.innerHTML = value;
document.appendChild(el);
}
By doing the following, in JavaScript you will get all the children of the User1/A node:
var ref = firebase.database().ref('User1/A');
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
//....
});
});
From there you can populate your HTML table
I'm using firebase to make a chat application. I stumbled upon a little problem.
When making requests to the firebase database, firebase will return a JSON or JS object back (I'm new to this so I don't really know).
This is the structure of my database:
The first ID under the message tree is the client's ID which I get when a cidst connects to the application. The id's just below are the client'ID with whom the logged client chatted with and the Id below that is firebase generated ID for each message.
With this code (see below) I'm listening on the database to see if any messages have been added for notification purposes.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data) {
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs) {
if (msgs.hasOwnProperty(keys)) {
console.log(keys + " -> " + msgs[keys]);
messages.push(msgs[keys]);
}
}
}
The output of the code:
I'm getting an array with two objects. Until here everything works fine.
My problem is that I can't figure out how I can get my message properties from here using JavaScript since the Message-IDs are unknown.
What I mean is that I can't access the properties doing msgs[keys].id.message for example since ID is unknown.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data)
{
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs)
{
if (msgs.hasOwnProperty(keys)) {
console.log(keys , " -> " , msgs[keys]);
messages.push(msgs[keys]);
var k = msgs[keys];
for(var keys in k){
console.log( k[keys]);
}
//
}
}
You could iterate over your JavaScript object with the .forEach method, use Object.entries for this.
In the following code snippet, I am logging all message objects
const messages = {
kjzn5ef6ke2zlfzn: {
h6qjopdbgs5d6mv7f: {
gd73g4d5d9dvtjzj15: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
},
kdaz8bamd6kprmq78: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
}
}
}
};
Object.entries(messages).forEach(([id1, a]) => {
Object.entries(a).forEach(([id11, b]) => {
Object.entries(b).forEach(([id111, message]) => {
console.log(id1, '=>', id11, '=>', id111, ':', message)
});
});
});
I have Firebase database managing following structure.
-DATA
-New
-CONTENTS
-animals_animal1: 1
-foods_food10: 4
-foods_food6: 5
-girls_girl1: 2
-girls_girl5: 3
I want to get children's value by using orderByValue() as 1,2,3,4,5 manner using snaps.forEach in JavaScript. My code as follows.
exports.handleAddNewContentAndAddToNewEvent = functions.database.ref('/CONTENT_MANAGEMENT/DATA/CONTENTS/{contentId}')
.onWrite(event => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
var newContentsRef = event.data.ref.parent.parent.child('PACKS/New/CONTENTS');
return Promise.all([
newContentsRef.orderByValue().once('value')
]).then(function(snaps) {
snaps.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log('loaded', childKey);
// ...
});
});
});
However, I failed to get intended solution. How to get solution what I need?
Structure