javaScript startsWith method giving an error - javascript

I am getting an error when filtering an array with startsWith method.
Error: Cannot read property startsWith of undefined
Here is my array:
let testdata = [
{
_id: "5d0876833827c2176cae90df",
MobileNumber: "965XXXXXXX",
Keyword: "ACCESSORIES",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90df"
},
{
_id: "5d0876833827c2176cae90e0",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e0"
},
{
_id: "5d0876833827c2176cae90e1",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
COMFORT, DEALS, DISCOUNT, DRESS, DRESSES, EXCHANGE, FASHION,
GIFT, GIFT CARD, GLASSES, HAIR.",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e1"
},
{
_id: "5d08c7c79d70334824470fb4",
Name: "JOHN",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "SMITH",
Gender: "M",
DateStamp: 1560856519847,
id: "5d08c7c79d70334824470fb4"
},
{
_id: "5d08c7c79d70334824470fb6",
Name: "ANTHONY",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "JR",
Gender: "M",
DateStamp: 1560856519848,
id: "5d08c7c79d70334824470fb6"
},
{
_id: "5d0884ef3827c2176cb2a970",
MobileNumber: "96170359896",
PlateNumber: "NULL",
CarModel: "NULL",
CarType: "NULL",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a970"
},
{
_id: "5d0884ef3827c2176cb2a971",
MobileNumber: "961XXXXXXXX",
PlateNumber: "P293676",
CarModel: "SEDAN",
ProductionDateOfCar: 1483228800000,
PurchaseDateOfCar: 1499281200000,
CarType: "HONDA",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a971"
}
];
console.log(testdata.filter(d => d.Keyword.startsWith('ACCESS))); //getting error
i was expecting to have all the records those start with 'ACCESS'.
How to apply startsWith method on multiple objects having different properties within same array?

You need to check if the Keyword property exists first :
console.log(testdata.filter(d => d.Keyword && d.Keyword.startsWith('ACCESS')));

You have plenty of objects that don't have the KeyWord property, so you have to account for those cases too:
testdata.filter(d => d.KeyWord && d.Keyword.startsWith('ACCESS'));
Or, if the KeyWord property can potentially be of a type other than string:
testdata.filter(d => typeof d.KeyWord === 'string' && d.Keyword.startsWith('ACCESS'));

there are some objects which does not have keyword. First check of its existence.
console.log(testdata1.filter(d =>d.Keyword ? d.Keyword.startsWith('ACCESS') : false))

Related

MongoDb - Delete Json object from array

I would like to delete an object from a JSON objects array. Here is the schema
qualifications: {
Experience: [{
title: String,
companyName: String,
location: String,
years: Number
}],
Education:[ {
school: String,
years: Number,
}],
Licences: [String],
Honnors: [String],
}
For example how can I delete the object whose key is "school": "harvard university" ?
What i tried is
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$pull: {
qualifications: {
Education: {
school: "harvard university",
}
},
},
}
);
But unfortunatelly it doesn't get deleted from the database. what is wrong?
can you try:
await User.update({ _id: req.body.userid },
{
"$pull": {
"qualifications.Education": {
"school": "harvard university",
},
},
});
qualifications is an object, thus you can't use the $pull operator which requires an array field. Instead, you need the (.) dot notation to update the nested Education array: qualifications.Education.
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$pull: {
"qualifications.Education": {
school: "harvard university"
}
}
})
Demo # Mongo Playground
Updated
From your error message, it seems qualifications is an array instead of an object. Your schema should be as below:
qualifications: [{
Experience: [{
title: String,
companyName: String,
location: String,
years: Number
}],
Education:[ {
school: String,
years: Number,
}],
Licences: [String],
Honnors: [String],
}]
To remove the object from the nested arrays, the below query aims to remove all the objects with school: "harvard university" from the Education array, for the all objects in the qualifications array,
const user = await User.findOneAndUpdate(
{
_id: req.body.userid,
"qualifications.Education.school": "harvard university"
},
{
$pull: {
"qualifications.$[].Education": {
school: "harvard university"
}
}
})
Demo (remove object from nested arrays) # Mongo Playground

Filtering an object by multiple arguments(inputs)

I have a lot of inputs, after which my object is supposed to filter, I can hardcode it, but there is probably a smarter way to do it
Filter state :
const [filters, setFilters] = useState<FiltersType>({
login: "",
name: "",
surrname: "",
});
Example data:
const data: UserRow[] = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
data.filter((e) => {
if (
(!filters.name || e.name.includes(filters.name)) &&
(!filters.surrname || e.surrname.includes(filters.surrname)) &&
(!e.login ||
e.login.toLowerCase().includes(filters.login.toLowerCase()))
) {
return true;
}
return false;
})
For example, it can be done like this, but as you can see it looks bad and scales poorly when adding new fields, I tried to simplify it using "Object.entries()", but ultimately failed :(. What is the best pattern for such a problem?
You should use some() (logical OR for all the conditions) or every() (logical AND for all the conditions) in combination with filter().
const data = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
const filter = {
login: "",
name: "",
surrname: "",
};
const filters = Object.entries(filter);
const filtered = data.filter((user) =>
filters.some(
([key, value]) =>
user[key] && user[key].toString().toLowerCase().includes(value)
)
);
console.log(filtered);
Use some() if you want to include the result if any of the filter conditions is met and use every() if you want to only include a result if all filter conditions are met.
The above will work for simple filters. You can however extend the solution using typeof() or Array.isArray() function etc. to process different types like arrays, nested objects etc. accordingly.

JavaScript (ReactJS) comparing two Objects

I have an object with users:
const data = [
{
name: "John",
lastName: "Doe",
email: "stefa#gmail.com",
password: "123",
following: [{ id: "113"}, { id: "111" } }],
id: "112",
},
{
name: "Jane",
lastName: "Doe",
email: "dusica#gmail.com",
password: "123",
following: [{ id: "112" }],
id: "113",
},
{
name: "Mark",
lastName: "Twain",
email: "marko#gmail.com",
password: "123",
following: [],
id: "111",
},
];
As you can see all users have an array named "following", and that array contains id's of users which the user follows. I want to access that array "following" to find out which users are not followed. Let's say that we want to check the "following" array of the first user John Doe with id="112".
const followers = [];
let suggestions = null;
props.users.forEach((user) => {
if (user.id === '112') {
user.following.forEach((item) => {
followers.push(item);
});
}
});
followers.map((item) => {
suggestions = props.users.map((user) => {
if (user.id !== item.id && user.id !== '112) {
console.log(item.id);
return <div>something</div>;
}
});
});
I tried something like this, but the result is not what i expected to be. As i said, i want to return users that are not followed and render them because i want them to be visible so the user can follow them. I hope that i was understandable enough. Thanks.
It's a negative comparison.
So you want to filter out all users that a user IS following.
You can loop through each user and compare it against the following array. If the following array contains the user then don't show it.
const notFollowing = allUsers.filter(user =>
!currentUser.following.some(({ id }) => id === user.id)
);

forEach nested to match

Here i made a code.
let StaffParsed = JSON.parse(params.StaffJson);
console.log(StaffParsed)
Here is the result below fo console log.
Object
cellPhoneNo: "1234567890"
createdBy: "1"
createdDate: "2020-05-09T17:26:31.743"
email: "ravi#email.com"
fax: "1234567890"
firstName: "Ravi"
id: 1004
lastName: "Nikam"
phoneNo: "1234567890"
profilePic: ""
sendEmail: false
sendPhone: false
status: "3"
title: "Mr."
type: "2"
updatedBy: "1"
updatedDate: null
username: "ravi109"
__proto__: Object
I have this model created here is the code below.
public StaffModel : Staff = new Staff();
console.log(this.StaffModel);
Its console log result is below.
Staff
CellPhoneNo: 0
CnfPassword: ""
CreatedBy: ""
CreatedDate: null
Email: ""
Fax: 0
FirstName: ""
FormStaffGroup: FormGroup {validator: null, asyncValidator: null, pristine: true, touched: false, _onCollectionChange: ƒ, …}
Id: null
LastName: ""
Password: ""
PhoneNo: 0
ProfilePic: ""
SendEmail: false
SendPhone: false
Status: "0"
Title: ""
Type: "0"
UpdatedBy: ""
UpdatedDate: null
UserName: ""
__proto__: Object
enter code here
Now i want to match with the above first object list with the second list and update the second list model, so far i have tried this code.
Object.keys(StaffParsed).forEach(function(keyParsed) {
Object.keys(this.StaffModel).forEach((keyModel: string) => {
if(keyParsed == keyModel){
keyParsed = this.StaffModel[keyModel];
}
});
});
But in return, it shows error like this .
Your problem is this part:
... .forEach(function(keyParsed) {
Object.keys(this.StaffModel)
this does not propagate into functions like that. As such, the this inside the function has a different value from the this in the outside function.
If you want the function to inherit the this of the outside scope, use an arrow function instead. ((keyParsed) => { instead of function(keyParsed) {)
In your code this in this.StaffModel[keyModel] may refer to the function not global.
Try this:
let that = this;
Object.keys(StaffParsed).forEach(function (keyParsed) {
Object.keys(that.StaffModel).forEach((keyModel: string) => {
if (keyParsed == keyModel) {
keyParsed = that.StaffModel[keyModel];
}
});
});

Push data to MongoDB without editing the whole entry in MEAN

So i've got a single page application running via MEAN Stack. I've got the following scheme/model for a Klausur (Klausur is german for exam, i want to manage exams).
var KlausurSchema = new Schema(
{
name: String,
semester: String,
krankmeldungen: [Number],
aufgaben: [{
name: String,
punkte: Number
}],
studenten: [{
matrnr: Number,
vorname: String,
nachname: String,
bewertung: [{
punkte: Number
}],
pversuch: String,
pvermerk: String,
freiverm: String,
labnr: Number,
porgnr: Number,
aenddat: String
}]
}
);
Multiple users can edit the entrys, otherwise i would just overwrite the entry. I want to have a table consisting of the "studenten" (students), is it possible to PUSH one student to my "studenten" without PUTTING (edit) the whole "Klausur", i.e. I want to push information to an array without overwriting the whole db entry!
Thanks in advance!
Please Check Docs
If you want to insert new students array. you can use below mentioned MongoDB query.
Using MongoDB
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
},
{
matrnr: 124,
vorname: "ABCD",
nachname: "XYZA",
bewertung: [{
punkte: 1234
}]
}]
}
);
Using Mongoose
ModelName.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}]
}
);
you can also use $push instead of $addToSet. but $addToSet handle duplicates insertion issue. One more thing if you want to add single student object then just use above query without $each. for example
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}
}
);
Pass an object to be updated to native mongoDB update query.
The pseudo query will be,
db.model.update(selector, objectToUpsert);
db.student.update(
{ name: "David" },
{
name: "Will",
marks: 75,
grade: A
},
{ upsert: true }
)
First find Klausur=exam say
Klausur.findOne({_id:sample_id}).exec(function (error, closure){
closure.students.push(newstudentobject);
closure.save();
})

Categories

Resources