Hey everyone İ am trying to write a function that accepts property name as an argument and deletes it. But i want a do it dynamically so i can change it anytime i want with other properties but i cant seem to make it. Help is much appreciated.
const student = {
names: "David Rayy",
sclass: "VI",
rollno: 12,
deleteProperty(property) {
console.log(property)
delete property
console.log(student)
},
}
student.deleteProperty(this.rollno)
like that ?
const student =
{ names : 'David Rayy'
, sclass : 'VI'
, rollno : 12
, deleteProperty(property)
{
console.log('delete ->', property)
delete this[property]
console.log(this)
}
}
student.deleteProperty('rollno')
You should be passing in a string as an argument to the function so that it can be used as the property name.
const student = {
name: 'David Rayy',
sclass: 'VI',
rollno: 12,
deleteProperty(property) {
delete this[property];
}
}
student.deleteProperty('rollno');
console.log(`
Name: ${student.name},
Class: ${student.sclass},
Rollno: ${student.rollno}
`);
Modern JS veers towards using classes. So an alternative solution might be to create a Student class that accepts some arguments, and has a deleteProperty
method. Then create a new student instance with that data, and then you can delete the property you want.
class Student {
constructor(name, sClass, rollNo) {
this.name = name;
this.sClass = sClass;
this.rollNo = rollNo;
}
deleteProperty(property) {
delete this[property];
return this;
}
print() {
console.log(this);
}
}
const student = new Student('David', 'VI', 12);
student.print();
student.deleteProperty('rollNo').print();