Add new key value pair to existing Firebase - javascript

This might be a pretty basic question, but so far I can't find the answer to my problem online after much googling. I have a firebase web app where the data structure is pretty simple. Initially, it's empty, like this:
fireRef {
}
I want to be able to add key value pairs where the key is created by the user and the value is just some text. For instance, the user would enter their name as the key, and the value as their age. Then I want to send that data to the server and have the firebase now look like this:
fireRef {
John : 25,
}
I can accomplish this one addition with:
var name = getUserName();
var age = getUserAge();
var node = {};
node[name] = age;
fireRef.set(node);
However, I want multiple people to be able to do this. When I try to add a new person to the server, the old "John : 25" pair turns red and disappears, leaving only the new key value pair.
How can I keep both around, and maintain a dataset of a bunch of key, value pairs?

The unique id in firebase is generated when we push data.
For example:
var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
var newUserRef = fireRef.push();
newUserRef.set({ 'name': 'fred', 'age': '32' });
Another way is to directly set the child elements:
var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
fireRef.child(1).set({'name':'user2','age':'34'});
fireRef.child(2).set({'name':'user3','age':'24'});

#user3749797, I got confused with this exact problem.
#learningloop offered a good solution, because it achieves the task of adding data to your firebase, but there is an option to add a new k,v (name, age) pair into a single JSON associative array rather than push to an array of associative arrays. Effectively, #learningloop sees:
[
{
name: steve,
age: 34
},
{
name: mary,
age: 22
}
]
Perhaps his way is better, but you and I were looking for this:
{
steve: 34,
mary: 22
}
I've managed to add to this list of k,v pairs with
var fireRef = new Firebase('https://<CHANGE_APP_NAME>.firebaseio.com/fireRef');
fireRef.update({ 'jobe': '33'});
Yielding
{
steve: 34,
mary: 22,
jobe: 33
}
In my firebase.
Full documentation on saving to firebase [here]

Just to add bit more clarity to #Charlie's answer:
Following works for me:
admin.database().ref(SITE).child("ChildName").child("2ndLevelChild") .update({[KeyVariable]:valueVariable});
Aparently if I were to use it like the following it doesnt work (it overwrites:
var newChild = {};
newChild["ChildName/" + "2ndLevelChild"] = {
[KeyVariable]: valueVariable
};
admin.database().ref(SITE).update(newChild);

Related

Find a string within a jQuery array that has multiple elements per object

I've got an array of employee's and assigned to each employee are a few elements.
Sample of array below:
var employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
I've got a means of gathering the employee's last name and I'm storing it in a variable. I'd like to be able to search for the indexOf the last name housed in this variable so that I know at which position within the array that match is made.
So for instance, this array could be 100 items in size. Ideally I want to know that someone with the last name of "johnson" is in position 50 of this array. That way, I can go in and get the salary and email associated with their record from position 50 in the array.
The code I've got so far is this:
var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);
This isn't working though - my console is logging -1, suggesting that it doesn't exist in the array. Is there a way that I can specify a element of that array to search against?
Almost like employees(name).indexOf(lname) where it is searching against the name element?
Or am I going about this all wrong and there is perhaps an easier less messy way to accomplish this?
You can use .findIndex:
const employees = [
{"name":"Johhny Test","salary":"1","email":"abc#123.com"},
{"name":"Mike Milbury","salary":"10","email":"184895#hdsjhfs.com"}
];
const lastName = "Test";
const index = employees.findIndex(employee => {
const { name = '' } = employee;
const nameParts = name.split(' ');
const lname = nameParts[nameParts.length-1];
return lastName === lname;
});
console.log(index);
console.log(employees[index]);

Javascript ForEach on Array of Arrays

I am looping through a collection of blog posts to firstly push the username and ID of the blog author to a new array of arrays, and then secondly, count the number of blogs from each author. The code below achieves this; however, in the new array, the username and author ID are no longer separate items in the array, but seem to be concatenated into a single string. I need to retain them as separate items as I need to use both separately; how can I amend the result to achieve this?
var countAuthors = [];
blogAuthors = await Blog.find().populate('authors');
blogAuthors.forEach(function(blogAuthor){
countAuthors.push([blogAuthor.author.username, blogAuthor.author.id]);
})
console.log(countAuthors);
// Outputs as separate array items, as expected:
// [ 'author1', 5d7eed028c298b424b3fb5f1 ],
// [ 'author2', 5dd8aa254d74b30017dbfdd3 ],
var result = {};
countAuthors.forEach(function(x) {
result[x] = (result[x] || 0) + 1;
});
console.log(result);
// Username and author ID become a single string and cannot be accessed as separate array items
// 'author1,5d7eed028c298b424b3fb5f1': 15,
// 'author2,5dd8aa254d74b30017dbfdd3': 2,
Update:
Maybe I can explain a bit further WHY on what to do this. What I am aiming for is a table which displays the blog author's name alongside the number of blogs they have written. However, I also want the author name to link to their profile page, which requires the blogAuthor.author.id to do so. Hence, I need to still be able to access the author username and ID separately after executing the count. Thanks
You could use String.split().
For example:
let result = 'author1,5d7eed028c298b424b3fb5f1'.split(',')
would set result to:
['author1' , '5d7eed028c298b424b3fb5f1']
You can then access them individually like:
result[1] //'5d7eed028c298b424b3fb5f1'
Your issue is that you weren't splitting the x up in the foreach callback, and so the whole array was being converted to a string and being used as the key when inserting into the results object.
You can use array destructuring to split the author name and blog id, and use them to optionally adding a new entry to the result object, and then update that result.
countAuthors = [
['author1', 'bookId1'],
['author2', 'bookId2'],
['author1', 'bookId3'],
['author1', 'bookId4'],
['author2', 'bookId5']
]
var result = {};
countAuthors.forEach(([author, id]) => {
if (result[author] === undefined) {
result[author] = {count: 0, blogIds: []};
}
result[author].count += 1;
result[author].blogIds.push(id);
});
console.log(result);

Dynamic Associative Array

In my application, I want to associate Country with its ID like this:
var Country = {
'France': 15,
'Canada': 26,
'Italy': 32
};
My database return to me an Associative Array and I can easily take all data I want to use.
for the moment I use that but my "push" don't want to use my variable "pays" ...
var pays = data[i].pays.nomFR;
allPays = [];
allPays.push({pays : data[i].pays.id});
Problem solved!
var pays = data[i].pays.nomFR;
allPays = new Array();
allPays[pays] = data[i].pays.id;
my push function was not the good one. That make exactly what I want!
:)

Grouping / counting in javascript using underscore.js

I am new to javascript (and to Stack Overflow) and I've encountered a problem I can't seem to solve. I am trying to generate a simple pie chart that shows the number of Projects for each value of Technology in my data. This is the kind of data I am working with:
[Project1, Java]
[Project2, Excel]
[Project3, SAS]
[Project4, Java]
The pie ratio in the example above would be 2:1:1.
The first part of my code loads the data and pushes it to an array, "techArray", that contains [project, tech]. This part works ok - I've verified it in a simplified version of the code.
I then want to group the array "techArray" and count the instances of each tech. To do so I'm using the Underscore library, as follows:
var chartData = [];
var techData = _.groupBy(techArray, 'tech');
_.each(techData, function(row) {
var techCount = row.length;
chartData = push( {
name: row[0].tech,
y: techCount
});
});
The script then renders the chartData array using highcharts. Again, I have verified that this section works using a simplified (ungrouped) version.
There must be an issue with the grouping/counting step outlined above because I am seeing no output, but I simply can't find where. I am basing my solution on the following worked example: Worked example.
If anyone can spot the error in what I've written, or propose another way of grouping the array, I'd be very grateful. This seems like it should be a simpler task than it's proving to be.
countBy could be used instead of groupBy:
var techArray = [
{ project: 'Project1', tech: 'Java'},
{ project: 'Project2', tech: 'Excel'},
{ project: 'Project3', tech: 'SAS'},
{ project: 'Project4', tech: 'Java'},
];
var counts = _.countBy(techArray,'tech');
This will return an object with the tech as properties and their value as the count:
{ Java: 2, Excel: 1, SAS: 1 }
To get the data in the form for highcharts use map instead of each:
var data = _.map(counts, function(value, key){
return {
name: key,
y: value
};
});
This should work
var techArray = [['Project1','Java'], ['Project2', 'excel'], ['Project3', 'Java']];
var chartData = [];
var techData = _.groupBy(techArray, function(item) {
return item[1];
});
_.each(techData, function(value, key) {
var techCount = value.length;
chartData.push({
name: key,
y: techCount
});
});
_.groupBy needs to either get a property name, or a function that returns the value being grouped. There is no tech property of an array, so you cant group by it. But, as our techArray is an array of tuples, we can pass a function _.groupBy that returns the value that we want to groupBy, namely the second item in each tuple.
chartData now looks like this:
[{
name: 'Java',
y: 2
}, {
name: 'excel',
y: 1
}]

How to apply complex data filters like SQL where clause on JSON

I am Using Json to represent data at client side(javascript), I converted .net datatable object to json and now need to apply filter on Json data. I used _.where to apply basic data filter , but need complex filtering like:
where = (stundentID = 55 and school='abc') AND (City='xyz' or City ='abc')
Its a basic type of filtration that we used in Oracle or sql server queries. Now how can i apply such mechanism using underscore.js or some thing equivelant on Json or javascript structures. I might also need to do query of getting Top N record , using aggregation [ Sum(sales)==500] at javascript. Waiting for your valuable suggestions.
Thanks,
Assuming you have this JSON represented as a regular JavaScript object—there's no such thing as a JSON object, after all—you're best bet would likely be to use linq.js
You'd be able to do things like:
var studentFilteredArray =
Enumerable.From(students)
.Where(function(s) { return s.studenId == 55; })
.OrderBy(function(s) { return s.LastName; })
.ToArray();
Or from your example above:
.Where(function(s) {
return s.studentID === 55 && s.school === 'abc' && (s.City === 'xyz' || s.City === 'abc')
});
You also can try alasql.js, where you can use standard SQL SELECT WHERE statement. Alasql was specially designed to work with JSON arrays like tables in database.
// Create database and describe the table
var db = new alasql.Database();
db.exec('CREATE TABLE students ([studentID] INT, school STRING, [City] STRING)');
// Assign you array here
db.tables.students.data = [
{studentID: 55, school: 'abc', City:'abc'},
{studentID: 56, school: 'klm', City:'xyz'},
{studentID: 57, school: 'nyz', City:'xyz'}
];
// Use regular SQL
console.log(db.exec("SELECT * FROM students "
+" WHERE ([studentID] = 55 AND school='abc') AND ([City]='xyz' OR [City] ='abc')"));
Try this example in jsFiddle.

Categories

Resources