Pergunta

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;
}}
Foi útil?

Solução

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": []
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top