0

I've tried searching this online but I usually find code that removes based on index and not on the actual value.

var arrDefaultLoanTypes = {
    1:"Regular Loan",
    2:"Emergency Loan",
    3:"Special Loan",
    4:"Instant Loan",
    5:"Financing",
    6:"Housing Lot Loan",
    7:"Salary Loan",
    11:"Appliance Loan",
    12:"Motorcycle Loan",
    13:"Educational Loan",
    17:"Grocery Loan"
};

I have a variable called selectedLoanType which serves as an indicator on what to remove. Example "Emergency Loan" or "Regular Loan" should be removed regardless of the value on the left hand side

e700867
  • 41
  • 9

1 Answers1

0

Just looping over the object and deleting the key/value pair if the value matches feels like the most straightforward (and most performant) approach in this case:

const arrDefaultLoanTypes = {
    1:"Regular Loan",
    2:"Emergency Loan",
    3:"Special Loan",
    4:"Instant Loan",
    5:"Financing",
    6:"Housing Lot Loan",
    7:"Salary Loan",
    11:"Appliance Loan",
    12:"Motorcycle Loan",
    13:"Educational Loan",
    17:"Grocery Loan"
};

const removeByValue = (object, value) => {
  for (let key in object) {
    if (object[key] === value) {
      delete object[key];
      break; // can break if values are guaranteed to be unique
    }
  }
}

removeByValue(arrDefaultLoanTypes, 'Regular Loan');
removeByValue(arrDefaultLoanTypes, 'Emergency Loan');

console.log(arrDefaultLoanTypes);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156