This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
A firebase event which listents for changes.
exports.sendTestEmail = functions.database.ref('/email/{pushID}')
.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;
}
return sendTestEmail(event);
});
function sendTestEmail(email, event) {
const users = event.data.val();
console.log(users);
});
}
this is the result for console.log(users):
{ '-Km8VHEPHExBtpIN_7q0':
{ admin: 'false',
birthday: '76',
description: 'desc',
email: 'user#gmail.com',
first_name: 'fname',
last_name: 'lname',
level: 5,
occupation: 'dev',
occupationLevel: 'dev5',
phone: '+8766',
verified: false },
'-KmSjAaxdCUvrPEQ8InI':
{ admin: 'false',
birthday: '1990',
description: 'desc',
email: 'email2#gmail.com',
first_name: 'fname',
last_name: 'lanam3',
level: 4,
occupation: 'dev',
occupationLevel: 'dev4',
phone: '+23434',
verified: false } }
I can't seem to loop and get the emails which are needed for sending emails to users who own the email addresses.
Maybe consider something like this.
function sendTestEmail(event) {
emails = []; // create empty email array
const users = event.data.val(); // get users, as you currently were.
for (var key in users) { // loop through users to retrieve key.
var email = users[key].email; // get email using key
emails.push(email); // push to emails array
}
return emails;
}
Related
i tried both .save and .update but it cause an error, --in the case of .save it return error: the value of a duplicate key breaks the unique constraint --in .update case it return error: the "userId" column of the "user" relation does not exist
note: i have 2 tables role and user and the association user_role
//Many-to-many relation with user
#ManyToMany((type) => User, (user) => user.roles)
users: User[];
//Many-to-many relation with role
#ManyToMany((type) => Role, {
cascade: true,
})
#JoinTable({
name: "users_roles",
joinColumn: { name: "userId", referencedColumnName: "id" },
inverseJoinColumn: { name: "roleId" }
})
roles: Role[];
the source code is :
/* exemple of data
entity2 = {
username: 'user8',
password: 'user8',
firstname: 'test',
lastname: 'tt',
email: 'user8#gmail.com',
company: 18,
roles: [ { id: 62 }, { id: 63 } ]
} */
let entity = await this.userRepository.create(data.payload);
let entity2 = { ...entity, roles: data.payload.selectedRoles }
const user = await this.userRepository.save(entity2);
/*const user = await this.userRepository.update(id, entity2);*/
//todo we need to serialize the user
// return only what we need like username , email, ...etc not password!!!!
return { success: true, user: SanitizeUser(user) };
I did findone then .save, 1st get the data to update using data= this.userRepository.findOne(id) then you can apply userRepository.save(data) to this data. for example :
const userUpdated = await this.userRepository.findOne(id)
let dataUpdated = {
...userUpdated,
username: data.payload.username,
firstname: data.payload.firstname,
lastname: data.payload.lastname,
email: data.payload.email,
company: data.payload.selectedCompany,
roles: data.payload.selectedRoles
}
const user = await this.userRepository.save(dataUpdated);
I have this code:
let peopleInRoom = [];
for (let message of messages) {
for (let email of message.user.email) {
if (!peopleInRoom.includes(email)) {
peopleInRoom.push(email);
}
}
}
let peopleInRoomElement = peopleInRoom.map(person => (
<li>{person}</li>
))
Basically I am trying to get all the unique emails and display them.
Is there a shorter and more efficient way (maybe some ES6 features) to write the same code? Seems too much code than needed.
I looked at this answer: How to get distinct values from an array of objects in JavaScript?
EDIT: Above code does not do what I want.
My data looks like this:
[
{
text: 'foo',
user: { email: 'foo#bar.com', password: 'foo' }
},
{
text: 'baz',
user: { email: 'baz#qux.com', password: 'baz' }
}
]
The objects are all messages. And I want to get an array of all the unique emails from each message
You can use the Set object that is built into JavaScript. Set object actually keep the distinct primitive values.
const messages = [
{
text: 'foo',
user: { email: 'foo#bar.com', password: 'foo' }
},
{
text: 'baz',
user: { email: 'baz#qux.com', password: 'baz' }
}
]
const peopleInRoom = [...new Set(messages.map(message => message.user.email))];
It actually extracts the email from each message and then passes it to the Set object which only keeps the unique set of emails. After that, it will spread that Set to the array, since Set is also an iterable and returns the array of the people in room.
If I understand correctly, people have messages, messages have email addresses and the OP seeks the unique set of email addresses. If that's all the data available, then there's no alternative but to iterate it, checking to see if each email has been collected already, and collecting it if it hasn't been.
There are ways to conceal this work by doing it in library code. Probably the highest level utility is lodash's _.uniqueBy, but the work must be done one way or another.
The Set object enforces uniqueness of its elements. You can use it this way:
const peopleInRoom = Array.from(new Set(messages.map(message => message.user.email)));
First you can make an array of all the email addresses:
const data = [
{
text: 'foo',
user: { email: 'foo#bar.com', password: 'foo' }
},
{
text: 'baz',
user: { email: 'baz#qux.com', password: 'baz' }
}
]
const emailArray = data.map((elem) => {
return elem.user.email;
}
and then you can filter them to be unique:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
emailArrayFiltered = emailArray.filter(onlyUnique);
see here for ref link
What about:
const peopleInRoom = messages.map(e => e.user.email && e.user.email);
console.log(peopleInRoom)
gives you this output:
["foo#bar.com", "baz#qux.com"]
This question already has answers here:
How to deep merge instead of shallow merge?
(47 answers)
Merge two objects and overwrite the values if conflict
(4 answers)
Closed 2 years ago.
I have 2 objects .
userprofile = {
id: 1,
email: hello #gmail.com,
user: {
id: 1,
username: test,
}
}
userprofile2 = {
email: bye #gmail.com,
user: {
username: testtest,
}
}
What i wish to do is to merge userprofile and userprofile2 , or in a sense using userprofile2 to override userprofile.
Here is what i wish to obtain:
updatedprofile = {
id: 1,
email: bye #gmail.com,
user: {
id: 1,
username: testtest,
}
}
The application for this problem is because i have an update form which uses redux saga . The change in data is userprofile2 while the previous data is userprofile.
Is there a simple efficient way to do this?
You could use the spread operator. As the ... operator only performs a shallow merge, you will have to spread the nested user property as well.
const userprofile = {
id: 1,
email: "hello #gmail.com",
user: {
id: 1,
username: "test",
}
}
const userprofile2 = {
email: "bye #gmail.com",
user: {
username: "testtest",
}
}
const updatedProfile = {
...userprofile,
...userprofile2,
user: {
...userprofile.user,
...userprofile2.user,
}
};
console.log(updatedProfile)
'''
const users = []
const addUser = ({ id, username, room }) => {
// Clean the data
username = username.trim().toLowerCase()
room = room.trim().toLowerCase()
// Validate the data
if (!username || !room) {
return {
error: 'Username and room are required'
}
}
// Check for existing user
const existingUser = users.find((user) => {
return user.username === username || user.room === room
})
// Validate username
if (existingUser) {
return {
error: 'Username already exists!'
}
}
// Store user
const user = { id, username, room }
users.push(user)
return { user }
}
addUser({
id: 03,
username: 'rohan',
room: 'playground'
})
console.log(users)
'''
If I run this in console the output is [ { id: 3, username: 'rohan', room: 'playground' } ]
But again if i just comment out the call and print the array. It showing empty.
'''
//addUser({
// id: 03,
// username: 'rohan',
// room: 'playground'
//})
console.log(users)
'''
From first run the value stored in object so It must be in the users array forever. Why this is empty if I dnt add value?
The following demo features 2 separate objects (userObjA, and userObjB), an arrow function called addUser(...user) which can accept any number of given objects (because of the spread operator: ... magic) then returns said objects wrapped in an array of objects (users).
Note: no const were hurt during the demonstration -- healthy free range let are leveraged for painless declarations and assignments.
Demo
let userObjA = {
id: 3,
name: 'Rohan',
room: 'Suite 42'
};
let userObjB = {
id: 4,
name: 'Dell',
room: 'Single 601'
};
const addUser = (...user) => {
let users = [];
users.push(user);
return users.flat();
};
console.log(addUser(userObjA, userObjB));
I'm trying to use Vuelidate to controll the inputs of my form. I'm providing an input field for the firstname, the lastname, the nationality and the age of the customer.
In my application it's necessary to check if the first customer is at least 18 years old.
I've tried the following to do this:
validations: {
customers: {
$each: {
firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
nationality: { required },
age: {
isFirstCustomerValid: (value) => {
return value >= 18
}
}
}
}
}
Now the problem is that this applies to all customers which is not intended. Is there a way to only access the first element of the $each property?
You can try finding customer's index by 2 ways:
If you customer has unique id, then use:
const customerIndex = this.customers.findIndex(c => c.id === customer.id)
If not, you can try using lodash's method isEqual
const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))
Code sample:
validations: {
customers: {
$each: {
firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
nationality: { required },
age: {
isFirstCustomerValid: (value, customer) => {
// if your customer has valid unique id, you can find it by findIndex
const customerIndex = this.customers.findIndex(c => c.id === customer.id)
// OR you ccan try lodash library 'isEqual' method (https://lodash.com/docs/4.17.11#isEqual)
const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))
return customerIndex || value >= 18
}
}
}
}
}