0

How to mutate given argument in javascript?

So I have this object:

const form = computed(() => {
  selected_id: '',
  selected_name: '',
  other_value: ''
})

I use that object as the value for dropdown, currently I mapped it as:

const selectedContact = computed({
      get: () =>
        form.value.selected_id
          ? {
              id: form.value.selected_id,
              name: form.value.selected_name
            }
          : null,
      set: val => {
        form.value.selected_id = val?.id || ''
        form.value.selected_name = val?.name || ''
      }
    })

The problem is, the code above become quite repetitive and doest look good in my eyes, so I want to create a helper function for selectedSomething in other file, I write it like this:

// helper function for dropdown
export const selectedDropdown = (
  formId: any,
  formName: any,
  keyId = 'id',
  keyName = 'name'
) => {
  return computed({
    get: () =>
      formId
        ? {
            [keyId]: formId,
            [keyName]: formName
          }
        : null,
    set: val => {
      formId = val ? val[keyId] : ''
      formName = val ? val[keyName] : ''
    }
  })
}

My expectation is, when the dropdown option is choosen, it will trigger the setter and mutate the value given from argument. I call the helper function like this:

const selectedContact = selectedDropdown(
      form.value.selected_id,
      form.value.selected_name
    )

The problem is, it seems that the value in the form object is not mutated through the setter inside the helper function

1 Answers1

0

The solution I found is by passing the whole object and mutate the object reference, I modified the helper function like this:

// helper function for dropdown
export const selectedDropdown = (
  form: any,
  formId: any,
  formName: any,
  keyId = 'id',
  keyName = 'name'
) => {
  return computed({
    get: () =>
      form[formId]
        ? {
            [keyId]: form[formId],
            [keyName]: form[formName]
          }
        : null,
    set: val => {
      form[formId] = val ? val[keyId] : ''
      form[formName] = val ? val[keyName] : ''
    }
  })
}

and I call the helper function like this

const selectedContact = selectedDropdown(
      form.value,
      'selected_id',
      'selected_name'
    )

The result is as I expected, it mutate the value of supplier_id and supplier_name inside computed form object when I choose option from dropdown