Passing object key as javascript function argument

arguments, javascript, key-value, object, parameters

Solution

You can access a specific key with the array notation:

op_hours[key].push('shark')

where `key === "thu"` for example

would give you:

 op_hours = {

  "mon": ["apple","orange"],
  "tue": ["table", "chair"],
  "wed": ["shark", "dolphin", "jellyfish"],
  "thu": ["shark"],
  "fri": [],
  "sat": [],
  "sun": []
}

Problem

I have an object, op_hours, which has days of the week as keys from mon - sun, with arrays of strings as values (In my actual code the values are arrays of objects, but I have changed them to strings here for simplicity). How may I add/remove strings from a certain key by passing the required key into a function argument? For instance, ``` function add(somethingToAdd, op_hours, key) { var sample = op_hours.key; sample.push(somethingToAdd); op_hours.key = sample; return op_hours; } var op_hours = { "mon": ["apple","orange"], "tue": ["table", "chair"], "wed": ["shark", "dolphin", "jellyfish"], "thu": [], "fri": [], "sat": [], "sun": [] }; ``` I currently have to write 14 functions, seven for adding and seven for deleting as follows: ``` function addMon(miniObj, bigObj) { var sample = bigObj.mon; sample.push(miniObj); bigObj.mon = sample; return bigObj; }} ```

Original source

Related problems