Replace name and return an object - object

We need to keep track of the school students, but the data we currently have combines the students first and last names into a single name. You have been asked to separate the names to make the data easier to work with.
The makeStudentList function takes an object with a name property whose value will be a string consisting of a first name and a last name, separated by a space. The function should return an object.
The function should remove the name property, replace it with firstName and lastName properties, as shown in the examples below.
Examples:
makeStudentList({ name: "Hannah Fry", age: 4 })
// should return { firstName: "Hannah", lastName: "Fry", age: 4 }
makeGuestList({ name: "Paul Erdős", age: 6 })
// should return { firstName: "Paul", lastName: "Erdős", age: 6 }

function makeStudentList(student) {
const [firstName, lastName] = student.name.split(" ");
delete student.name;
student.firstName = firstName;
student.lastName = lastName;
return student;
} // should return { firstName: "Hannah", lastName: "Fry", age: 4 }
let response = makeStudentList({ name: "Hannah Fry", age: 4 });
const p = document.querySelector('p');
p.append(JSON.stringify(response));
<p></p>

def makeStudentList(name,age):
Name=name.split(" ")
return {"FirstName":Name[0],"lastName":Name[1],"Age":age}
makeStudentList("Hannah Fry",4)
Here you go, lemme know if you need any sort of explanation, cheers:)

Related

How to add a where clause dynamically to query which is generated using nestjs Query Builder?

I am working on an API for which the requirement from UI is based on the value of the search field I shall receive the filtered results. There are many search fields on UI.
Example code -
async getRoomsByMember(active: boolean, email: string): Promise<any[]> {
return await getRepository(Room)
.createQueryBuilder('room')
.innerJoinAndSelect('room.member', 'member')
.where("room.active = :active", {active: active})
.andWhere("member.email = :email", { email: email })
.getMany();
}
I shall be able to filter room members dynamically if values entered by a user on filter fields like - member phone number, city, state, country, and zip.
You're almost there :-)
You can try something like this:
async getRoomsByMember(active: boolean, email: string): Promise<any[]> {
const query = getRepository(Room)
.createQueryBuilder('room')
.innerJoinAndSelect('room.member', 'member')
.where("room.active = :active", {active: active});
// Keep adding your other fields like member phone number, city, state, country, and zip, like below
if(email) {
query.andWhere("member.email = :email", { email: email })
}
return query.getMany();
}

match all if the user doesn't specify the field value MongoDB

I am building an API where I have several fields that are optional in my get request. So I want MongoDB to match all values for those optional fields if the user does not specify it. I have come up with this solution:
db.collection(expenses_collection).find(username: username, category: {$regex:"/" + category + "/"}, payment_type: {$regex:"/" + payment_type + "/"}})
Where if category and payment_type are not specified by the user I set them to ".*":
const {category=".*", payment_type=".*"} = req.query;
However, mongodb is still not matching any data. Any help is appreciated. Thanks a lot.
The issue is with your regex string. To match any string value, you have to use this pattern (this matches any string): (.*?)
Consider input documents:
{ _id: 1, name: "John", category: "cat 1", payment_type: "cash" },
{ _id: 2, name: "Jane", category: "cat 2", payment_type: "credit card" }
Usage to match any category field value:
let categoryStr = /(.*?)/
db.exp.find( { category: categoryStr } )
The query returns all documents.
So, in your application for the category value not specified the code can be like this:
if (category is empty or null) { // category not specified by user
categoryStr = /(.*?)/
}
Similarly, for the payment_type field also.
Then query would be:
db.exp.find( {
username: usernameStr,
category: categoryStr,
payment_type: paymentStr
} )
NOTE: The code tests fine with MongoDB NodeJS driver APIs.
Isn't this what exists is made for?
{category: { $exists: true }, payment_type: { $exists: true }}

Access a specific property in Object.keys adonis.js (Node.js)

I have a query that returns an array, with Object.key (array) .foreach I am iterating, I want to know the value of a property in specific array.
Example:
Object.keys(arreglo).forEach(function(key) {
console.log(arreglo[key]);
});
The output is:
name: "Pepito",
Surname: "Perez"
I want to know how to get only the value of the surname
I know it will not work but it would be something like:
console.log(arreglo[key].surname);
You can use Array.forEach on the original array as shown below. You can even extract the fields you are interested using Array.map.
// let's assume the arrary you got from your query is in this format
const arreglo = [
{ firstname: "fn1", surname: "ln1"},
{ firstname: "fn2", surname: "ln2"},
{ firstname: "fn3", surname: "ln3"}
];
// you can log `surname` for each entry in the array
arreglo.forEach(v => console.log(v.surname));
// you can use map to transform the array to just have `surname` using array.map()
const surnames = arreglo.map(v => v.surname);
console.log(surnames);
Is this what you are looking for
const object1 = {
a: {firstname:"sali",lastname:"mali"},
b: {firstname:"sali",lastname:"mali"},
c: {firstname:"sali",lastname:"mali"}
};
Object.keys(object1).forEach(function(key){console.log(object1[key].lastname)});

Map an array of objects to another with multiple rows being similar in node express

I'm attempting to map an object to another, and I'm having trouble writting the loop correctly. Basically:
I have 1 object returned by my repository level. It has multiple rows based on the same username but with scores based on different courses thus:
row1 = userName Tim, courseScore 5
row2 = userName Tim, otherCourseScore 10
row3 = userName Mike, courseScore 4
row4 = userName Mike, otherCourseScore 7
and so on. I'd like to map this to a DTO object so that the data looks like this:
row1 = userName Tim, courseScore 5, otherCourseScore 10
row2 = userName Mike, courseScore 4, otherCourseScore 7
I'm having trouble writing the a loop that can go through the first object and map it to the DTO level. Here's what I currently have, but it's not mapping the data correctly.
for (let key in UserInformation) {
let usr = UserInformation[key].userName;
if (usr === UserInformation[key].userName) {
userScatterplotDTO.userName = UserInformation[key].userName;
userScatterplotDTO.judgmentScore = UserInformation[key].score;
}
}
Try something like this..
let rows = [{
userName: 'Tim',
type: 'courseScore',
score: 5
},
{
userName: 'Tim',
type: 'otherCourseScore',
score: 10
},
{
userName: 'Mike',
type: 'courseScore',
score: 4
},
{
userName: 'Mike',
type: 'otherCourseScore',
score: 7
}
];
let result = {
}
rows.forEach((row) => {
if (!(result[row.userName])){
result[row.userName] = {
userName: row.userName,
scores: []
};
}
result[row.userName].scores.push({
type: row.type,
score: row.score
});
});
console.log(result);

Match range for value with MongoDB

I have a campaign collection, which is for advertisers. It's schema is:
var campaignSchema = new mongoose.Schema({
name: String,
sponsor: String,
[...]
target: {
age: {
lower: Number,
upper: Number
},
gender: String,
locations: Array, // [ { radius: '', lon: '', lat: '' } ]
activities: Array
}
});
I need to run a query with a specific age, and return all campaigns where that age is between age.lower and age.higher.
I have read the docs for $gt and $lt, however they appear to only work one way (so I could specify a range and match a value, however I need to specify a value and match a range).
Any suggestions?
Sorry I misunderstood the problem, I got it now.
db.collection.find( { "age.lower": { $lt: value1 }, "age.upper": { $gt: value1 } } );
So, for example, if your range is 25 to 40, and value1 is 30, 25 < 30 and 40 > 30 -- match!
If you use the same range with 20, 25 !< 20 -- will not match.
You could first create a query on the lower bound of that value, sort the results in descending order and get the top document from the result. Compare that document with the upper bound, if there is a match then that document has a range which contains that age. For example:
var age = 23;
var ads = db.campaign.find({ "age.lower": {"$lte": age } }).sort({"age.lower": -1}).limit(1);
if (ads != null) {
var result = ads[0];
if (result.age.upper > age) {
return result;
} else {
return null;
}
}

Resources