Firebase, Anyway to create name dynamically - javascript

fredNameRef.set({ first: 'Fred', last: 'Flintstone' });
I want to create 'name' which is first and last name dynamically.
For Example :
var x = first_1;
var y = last_1;
fredNameRef.set({ x: 'Fred', y: 'Flintstone' });

If you are asking about auto-calculated value, Firebase doesn't have such a feature. You will have to pre-calculate the value as you write the name to the database:
fred = { first: 'Fred', last: 'Flintstone' };
fred.name = fred.first + ' ' + fred.last;
refNameRef.set(fred);
You could even validate that write operations don't violate this rule:
".validate": "newData.child('name').val() === (newData.child('first').val() + ' ' + newData.child('last').val())"

Related

Is there a solution to expect that a specific key is greaterThan value within objectContaining?

I'm doing a simple test similar to the following:
it("Must fail", () => {
const length = person.list().length;
expect(person.add({ name: "John", age: -5, gender: 'M' })).toEqual(
expect.objectContaining({
id: expect.any(Number),
name: expect.any(String),
age: expect.any(Number),
gender: 'M' || 'F', // only 'M' or 'F'
})
);
// to ensure that a new person was added
expect(person.list().length).toEqual(length+1);
});
The return of db.add is an object with the id included.
However, I would like to expect that age is not only any number, but also a number with an age greater than or equal zero.
I could use discrete values in gender or specify age: 0 || 1 || 2 || 3 || ..., but if I want to match the gender with an specific pattern match or specify that age is in a range of allowed values, how could I do that?
I cannot use expect(age) inside, as far as I know in my research to expect something about the value of keys.
It looks like you are trying to do to much in as few lines of code as possible which puts you in this situation, try something like this:
it("should set age to 0 when provided age is lower than 0", () => {
const storedPerson = person.add({ name: "John", age: -5, gender: 'M' });
expect(storedPerson.age).toBe(0);
});
If you want to check all values but you don't want to write 5 expect to do so, then try this:
it("should properly store new person", () => {
const length = person.list().length;
const expectedPerson = { id: expect.any(Number), name: "John", age: 0, gender: 'M' };
const storedPerson = person.add({ name: "John", age: -5, gender: 'M' });
expect(storedPerson).toEqual(expectedPerson);
expect(person.list().length).toEqual(length+1);
});
But to be honest I would recommend my first example. With the second one you would test to much in one test, checking proper validation of age, checking if id was added, checking properly assigned values and checking lists length. When that test fails you wouldn't know what went wrong based on the name of test. In unit tests, try to test as little as possible in one test.

I've object {name: 'John', 'surname': 'Johnson', 'age': '20'}

Please tell me, I need to write a function that writes the corresponding values
into the variables name, surname and age.
How can this be implemented?
let user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
let{name, surname, age} = user;
document.write(name + ' ' + surname + ' ' + age);
Ummm
function writeUser(user){
document.write(user.name + " " + user.surname + " " +user.age)
}
?
Let's see if this is something in the lines of what you're looking for:
const user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
function updateUser(user) {
user.name = "New name";
user.surname = "New surname";
user.age = "New age";
}
updateUser(user);
const { name, surname, age } = user;
document.write(name + ' ' + surname + ' ' + age);
By adding an other parameter to this function you might make it more useful, like this:
function updateUser(user, overrides) {
Object.assign(user, overrides);
}
updateUser(user, { age: '30', name: 'New name' });
This would change the age and name but leave the surname, but it modifies the input user which isn't really a good pattern, better to return a new object instead:
function updateUser(user, overrides) {
return Object.assign({}, user, overrides); // First assign user to the empty object, then assign the overrides to that new object
}

Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods

Please help me to write better code.
Suppose I have a JavaScript array like below:
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
On page I want to show data in two parts, 1)Students who got marks >= 40 2)Students who got marks < 40
By using for loop I done this functionality easily as below.
var data = "";var data1 = "";
for (var i = 0; i < students.length; i++ )
{
if(students.marks >= 40){
data += = students.firstname + " " + students.lastname; //actual data in html div tag
....
}else{
data1 += = students.firstname + " " + students.lastname;
}
}
I want to achieve same functionality by using JavaScript methods like map, reduce, foreach, filter etc. (want to improve my JavaScript knowledge)
Don't know exactly which method is useful for such functionality.
Used map method and tried to display data, but there is a trailing , at the end of each object/array.
Can anyone please help/guide me to write proper code?
Here is solution using filter and forEach methods, using callback functions.
See references here :
filter method
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
students.filter(function(item){
return item.marks>=40;
}).forEach(function(item){
div=document.getElementById('persons');
div.innerHTML+=item.firstname+' '+item.lastname+'<br>';
});
<div id="persons"></div>
You could use a single loop and add the information with predicate as index. Later join the elements for getting a sting for each element.
var students = [{ firstname: "stud1", lastname: "stud2", marks: "60" }, { firstname: "stud3", lastname: "stud4", marks: "30" }, { firstname: "stud5", lastname: "stud6", marks: "70" }, { firstname: "stud7", lastname: "stud8", marks: "55" }, { firstname: "stud9", lastname: "stud10", marks: "20" }],
predicate = function (o) { return o.marks >= 40; },
result = [[], []];
students.forEach(function (a) {
result[+predicate(a)].push(a.firstname + ' ' + a.lastname);
});
result = result.map(function (a) { return a.join(', '); });
console.log(result);

How to grab a single element passed from express JSON array and output in Jade

I have an array incoming from Express to a Jade template that looks like this:
[{ id: 11,
firstname: 'asdfasdf',
lastname: 'asdfasdf',
},
{ id: 12,
firstname: 'asdfadf',
lastname: 'asdfasdf',
}]
I want to grab one of these elements and display it along with its properties on the page.
I have read several other answers here but none seem to answer my question/work properly.
I have tried,
#{data[0].id}
!{data[0].id}
#{data.id[0]}
data.id[0]
data[0].id
...and countless other combinations, how can i print this out properly?
I know my data object is being passed in correctly because I can iterate through it using a for loop elsewhere in my page. But if I only want to grab ONE element ONLY from the array, how can i achieve this?
Is this even possible without looping through the entire json array object?
UPDATE: my problem was due to the array structure being different than what I initially thought it was. My mistake, the correct way to access elements is using
#{data[0].id}
This is an array of JSON objects so you need to iterate it through
var newObject = [{ id: 11,
firstname: 'asdfasdf',
lastname: 'asdfasdf',
},
{ id: 12,
firstname: 'asdfadf',
lastname: 'asdfasdf',
}];
for (var i = 0; i < newObject.length; i++) {
var object = newObject[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
}
or
var newObject = "[{ id: 11,firstname: 'asdfasdf',lastname: 'asdfasdf',},{ id: 12, firstname: 'asdfadf', lastname: 'asdfasdf',}]";
var obj = eval(newObject);
alert(obj[0].id);

How do I assign a function to the property of a Javascript object?

I was looking and struggling to the following example:
var player1= {name: "Chris", score: 1000, rank: 1};
var player2= {name: "Kristofer", score: 100000, rank: 2};
function playerDetails(){
alert("The name of the player is "+ this.name + "."+ " His score is : "+ this.score + "and his rank : "+ this.rank);
}
player1.logDetails= playerDetails;
player2.logDetails= playerDetails;
player1.logDetails();
player2.logDetails();
As far as I know player1.logDetails is a property of player1 or a method of player1.
So I can't understand how the author assigns a property to a function.
Also I don't get why you would write it like that instead of :
player1.logDetails= playerDetails();
which I have tried and doesn't work.
Then he calls player1.logDetails() which is a function but not declared anywhere.(?)
If anyone could help??
Thank you in advance
If the code was written like this, I bet you understand it:
var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: function() { alert('The name is '+ this.name) }
};
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: function() { alert('The name is '+ this.name) }
};
The author of the code wanted to define the "playerDetails()" function once.
Another way of showing this in a simplified manner is:
var player1 = {
name: "Chris",
score: 1000,
rank: 1
};
player1.playerDetails=function() { alert('The name is '+ this.name) }
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2
};
player2.playerDetails=function() { alert('The name is '+ this.name) }
So if you wanted to optimize the code above by only writing the playerDetails function once, it would look like the code in your post.
If I had written the code block, I might have written it like this: (which is easy to read)
function playerDetailsFunc() {alert('The name is '+ this.name) }
var player1 = {
name: "Chris",
score: 1000,
rank: 1,
playerDetails: playerDetailsFunc
};
var player2 = {
name: "Kristofer",
score: 10000,
rank: 2,
playerDetails: playerDetailsFunc
};
Javascript functions are no different from other values or objects.
You can assign them to whatever you want; you can even pass them as parameters.
I'm still a newb myself, but you could create the method in the object as an alternative.
var player1= {name: "Chris", score: 1000, rank: 1, logDetails: playerDetails};
var player2= {name: "Kristofer", score: 100000, rank: 2, logDetails: playerDetails};
function playerDetails(){
console.log("The name of the player is "+ this.name + "."+ " His score is : "+ this.score + "and his rank : "+ this.rank);
}
player1.logDetails();
player2.logDetails();
Also, the link below under "Defining Methods" may help answer your question.
enter link description here
var player1= {name: "Chris", score: 1000, rank: 1};
var player2= {name: "Kristofer", score: 100000, rank: 2};
playerDetails = player => console.log( "The name of the player is "+ player.name + "."+ " His score is : "+ player.score + "and his rank : "+ player.rank);
player1.logDetails= playerDetails(player1);
player2.logDetails= playerDetails(player2);

Categories

Resources