1

I have an associative array in my JS which I want to feed my Select.

These are the standard hours available that will refresh my availablehours (when page loads);

var standardhours = {
  "09" : '9AM',
  "10" : '10AM',
  "11" : '11AM',
  "12" : 'Noon',
  "13" : '1PM',
  "14" : '2PM',
  "15" : '3PM',
  "16" : '4PM',
  "17" : '5PM',
  "18" : '6PM',
  "19" : '7PM'
};

These the available hours that I want to feed my Select.

var availablehours = {
    "09" : '9AM',
    "10" : '10AM',
    "11" : '11AM',
    "12" : 'Noon',
    "13" : '1PM',
    "14" : '2PM',
    "15" : '3PM',
    "16" : '4PM',
    "17" : '5PM',
    "18" : '6PM',
    "19" : '7PM'
};

This is my dynamic variable that changes based on database changes. These are the hours taken by someone already.

takenHours = {"09", "18"};

I want to remove the takenHours from the availablehours associative array. Not sure how. The thought process I have feels very manual and simplistic.

2
  • 2
    That is an invalid object. Commented Aug 27, 2018 at 4:42
  • 2
    Should takenHours be an array like this? takenHours = ["09", "18"]; Commented Aug 27, 2018 at 4:48

1 Answer 1

5

If I understand correctly, then you should be able to achieve this kind of mutation of availablehours via the delete operator, as shown:

var availablehours = {
  "09": '9AM',
  "10": '10AM',
  "11": '11AM',
  "12": 'Noon',
  "13": '1PM',
  "14": '2PM',
  "15": '3PM',
  "16": '4PM',
  "17": '5PM',
  "18": '6PM',
  "19": '7PM'
};
console.log(availablehours);

var takenHours = ["09", "18"];

// Iterate through the hours to be removed
for (var takenHour of takenHours) {

  // For each hour key, use the delete operator to remove 
  // the key/value pair from availablehours completlty
  delete availablehours[takenHour]
}

// availablehours will no longer contain "09" or "18" key/value pairs
console.log(availablehours);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.