I am not able to assign dynamic name to my array (I want to assign value of auth_ID as name of array).
Problem - it is saving auth_ID as text in db, whereas i want its value.
Here is my code:
exports.insert_totalcalllogs = functions.firestore
.document('calllogs/{calllogsId}')
.onCreate(
async (snapshot: { data: () => { (): any; new(): any; entryDate_show:any; authid: any; fullname:any; }; },context:any) => {
// todos details.
const text = snapshot.data();
const entryDate_show = text.entryDate_show;
const auth_ID = text.authid; // want this to be name of array
const fullname = text.fullname;
admin.firestore().collection("totalcalllogs").doc(entryDate_show).set({
auth_ID: [
{ number: 1, fullname: fullname , authid: auth_ID},
],
age: 12,
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error: any) {
console.error("Error writing document: ", error);
});
...// some code
See image of console:
If you want to use a variable as the name of property in a JavaScript object, use the square bracket notation when building the object:
admin.firestore().collection("totalcalllogs").doc(entryDate_show).set({
[auth_ID]: [
{ number: 1, fullname: fullname , authid: auth_ID},
],
age: 12,
})
Note the square brackets around [auth_ID].
Related
I have this code that set the obj value in localstorage.
const obj = {
name: "Bill",
meta: {
age: 18
}
};
const data = localStorage.setItem('user', JSON.stringify(obj));
Now i want to change the age key in the localstorage:
localStorage.setItem('user', JSON.stringify({ ...data, ...data.meta.age= 15 } }));, but it does not work.
How to change the value above and to see the changes in localstorage?
Assuming you have data, the problem is that ...data.meta.age = 15 is a syntax error. You don't use = in object literals, and it does't make sense to try to spread the age property (which is a number). Instead:
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
localStorage.setItem("user", JSON.stringify(newData));
Notice how we have to create a new outermost object and also a new object for meta.
Live Example:
const data = {
name: "Bill",
meta: {
occupation: "Programmer", // Added so we see it get copied
age: 18,
},
};
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
console.log(newData);
I am trying to filter out empty array but its not happening
I was trying to compare value which are present inside my database and fileName
I tried arr.filter(Boolean);
even i tried arr.filter((item)=>item)
PS: fileName is not an array value so I converted it into array.
function checkDoc(data, childProduct, fileName, pathName, req, res) {
return new Promise((resolve, reject) => {
Document.findAll({
raw: true,
where: {
product_id: childProduct.id,
},
})
.then((productDoc) => {
if (productDoc.length === 0) {
return resolve(addDocument(data, childProduct, fileName, pathName));
} else {
let fileArray = [];
fileArray.push(fileName);
productDoc.forEach((singleProduct) => {
let productValue = singleProduct.name;
let unMatchedValues = fileArray.filter((value) =>
productValue.includes(value)
);
let removedBoolean = unMatchedValues.filter((item) => item);
console.log("Document Name: ", removedBoolean);
});
}
})
.catch(function (err) {
return reject("Can't be added please try again :) " + err);
});
});
}
fileName:
ABC
PQR
XYZ
Installation and Configuration
Java
Node Js
where as in singleProduct.name it contain
[ABC]
[PQR]
[Installation and Configuration]
[XYZ]
attached Output Image :
Expected OutPut:
matchedValue:
[`document name: ABC`]
[`document name: PQR`]
[`document name: Installation and configuration`]
[`document name: XYZ`]
unmatchedValue:
['Java']
[`Node Js`]
If you're asking how to filter an array of objects to remove those with empty names, here's an example:
const team = [
{ name: 'max', age: 21 },
{ name: '', age: 19 },
{ name: 'james', age: 33 },
{ name: '', age: 30 },
];
// Log the entire team
console.log('Team:', team);
// Log only those team members with names
console.log('Team with names:', team.filter(x => x.name));
// Log only the names
console.log('Names:', team.filter(x => x.name).map(x => x.name));
'''
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 create a set of reducers in order to change an attribute of all objects in a nested list.
The input payload looks like the following:
const payload = [
{
name: "Peter",
children: [
{
name: "Sarah",
children: [
{
name: "Sophie",
children: [
{
name: "Chris"
}
]
}
]
}
]
}
];
I now want to change the name attribute of all elements and child elements.
const mapJustNickname = elem => {
return {
...elem,
nickname: elem.name + "y"
};
};
How do I use this map function recursively on all child elements?
I found a way to do this by putting the the recursion within the same mapping function.
const mapToNickname = (elem) => {
return {
nickname: elem.name +'y',
children: elem.children && elem.children.map(mapToNickname)
}
}
console.log(payload.map(mapToNickname));
But I'd like to have the mapping of the name separated from the recursion (for reasons of keeping the mapping functions as simple as possible) and being able to chain them later. Is it somehow possible to do this with two reducers and then chaining them together?
Let's start by rigorously defining the data structures:
data Person = Person { name :: String, nickname :: Maybe String }
data Tree a = Tree { value :: a, children :: Forest a }
type Forest a = [Tree a]
type FamilyTree = Tree Person
type FamilyForest = Forest Person
Now, we can create mapTree and mapForest functions:
const mapTree = (mapping, { children=[], ...value }) => ({
...mapping(value),
children: mapForest(mapping, children)
});
const mapForest = (mapping, forest) => forest.map(tree => mapTree(mapping, tree));
// Usage:
const payload = [
{
name: "Peter",
children: [
{
name: "Sarah",
children: [
{
name: "Sophie",
children: [
{
name: "Chris"
}
]
}
]
}
]
}
];
const mapping = ({ name }) => ({ name, nickname: name + "y" });
const result = mapForest(mapping, payload);
console.log(result);
Hope that helps.
Create a recursive map function that maps an item, and it's children (if exists). Now you can supply the recursiveMap with a ever transformer function you want, and the transformer doesn't need to handle the recursive nature of the tree.
const recursiveMap = childrenKey => transformer => arr => {
const inner = (arr = []) =>
arr.map(({ [childrenKey]: children, ...rest }) => ({
...transformer(rest),
...children && { [childrenKey]: inner(children) }
}));
return inner(arr);
};
const mapNickname = recursiveMap('children')(({ name, ...rest }) => ({
name,
nickname: `${name}y`,
...rest
}));
const payload = [{"name":"Peter","children":[{"name":"Sarah","children":[{"name":"Sophie","children":[{"name":"Chris"}]}]}]}];
const result = mapNickname(payload);
console.log(result)
I have developed an Angular4 appln that calls a nodeExpressJS server to fetch JSON data and also adds data to the JSON object. The following is the onSubmit function of the addemployeeform.
onSubmit(formValue: any) {
console.log("Form Value = " + JSON.stringify(formValue, null, 4));
let newEmployee: Emp;
let last: any;
this._employeeService.lastEmployeeID().subscribe((last: any) => last = last,
err => console.log(err));
newEmployee = {
//id: employeeCount + 1,
id: last + 1,
name: formValue.name,
manufacturer: formValue.manufacturer,
type: formValue.type,
batchno: formValue.batchno,
expdate: formValue.expdate,
price: formValue.price
};
// console.log(newEmployee.id );
let temp = this._employeeService.addEmployee(newEmployee).subscribe(err =>
console.log(err));
this.router.navigate(['employees']);
}
But then it isn't pushing the id property to the JSON for newEmployee.
{id: 1, name: "Paracetamol", manufacturer: "Ranbaxy", type: "Tablet", batchno …}
{id: 2, name: "Sinarest", manufacturer: "GSK", type: "Tablet", batchno: …}
{id: 3, name: "Viagra", manufacturer: "Pfizer", type: "Capsule", batchno: …}
{name: "Aspirine", manufacturer: "Aspirine", type: "Syrup", batchno: "03/46", expdate: "03/04/2023", …}
newEmployee is Aspirine.
And on uncommenting console.log(newEmployee.id ); line of code
I get a Nan error
First, shouldn't last be defined as a number and not any?
Second, and more importantly, the lastEmployeeId call is most likely asynchronous, meaning it will not have completed before the next line of code is complete. You need to add all of the code that executes after that operation within the subscribe.
this._employeeService.lastEmployeeID().subscribe(
(last: any) => {
last = last;
newEmployee = {
//id: employeeCount + 1,
id: last + 1,
name: formValue.name,
manufacturer: formValue.manufacturer,
type: formValue.type,
batchno: formValue.batchno,
expdate: formValue.expdate,
price: formValue.price
};
// console.log(newEmployee.id );
let temp = this._employeeService.addEmployee(newEmployee).subscribe(
employee => {
console.log(employee);
this.router.navigate(['employees']);
},
err => console.log(err)
);
And with that much code in the first function passed to your subscribe, you may want to instead make it it's own function:
this._employeeService.lastEmployeeID().subscribe(
(last: number) => this.processEmployeeId(last),
err => console.log(err));
processEmployeeId(last: number) {
// Your code here.
}
if last is supposed to be a number type then state so:
let last: number;
If you're going to use typescript - you might as well use it to your advantage.