创建一个对象的函数如何实现?

huangapple go评论56阅读模式
英文:

How to implement a function to create an object?

问题

有一个对象:

const filters = ref<filterType>({
  date: {
    value: '',
  },
  user: {
    value: '',
  },
  userId: {
    value: '',
  },
  ...
})

有一个用于发送数据的函数,它以基于filtersref的对象作为参数:

({ 
  date: filters.value.date.value || undefined,
  user: filters.value.user.value || undefined,
  userId: filters.value.userId.value || undefined,
  ... 
})

然后我需要相同的对象,但在不同的函数中。为了不重复两个大对象,我可能需要实现一个函数来创建这个对象。如何正确实现它?

英文:

There is object:

const filters = ref&lt;filterType&gt;({
  date: {
    value: &#39;&#39;,
  },
  user: {
    value: &#39;&#39;,
  },
  userId: {
    value: &#39;&#39;,
  },
...

There is a function for sending data, to which an object is passed as a parameter based on filters's ref:

({ 
  date: filters.value.date.value || undefined,
  user: filters.value.user.value || undefined,
  userId: filters.value.userId.value || undefined,
  ... 
})

Then I need the same object that but in different function. In order not to duplicate two large objects, I probably need to implement a function that will create this object. How to implement it correctly?

答案1

得分: 0

您可以创建并导出一个基于 `filters` 返回对象的函数:

```ts
export const getFilterParams = (filters: filterType) => ({
  date: filters.value.date.value || undefined,
  user: filters.value.user.value || undefined,
  userId: filters.value.userId.value || undefined,
  ...
});

您可以像这样调用它:

const params = getFilterParams(filters.value);
英文:

You can create and export a function that returns the object based on filters:

export const getFilterParams = (filters: filterType) =&gt; ({
  date: filters.value.date.value || undefined,
  user: filters.value.user.value || undefined,
  userId: filters.value.userId.value || undefined,
  ...
});

You would call it like that:

const params = getFilterParams(filters.value);

huangapple
  • 本文由 发表于 2023年2月6日 21:00:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定