• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

161
Views
Deleting an object property with a function

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)
almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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')

almost 3 years ago · Juan Pablo Isaza Report

0

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();

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error