【问题标题】:Typescript Assign custom object to any object打字稿将自定义对象分配给任何对象
【发布时间】:2021-06-29 19:51:25
【问题描述】:

尝试使用代码https://github.com/chuvikovd/multi-column-sort 对表数据进行排序,但是如何将自定义对象传递给SortArray[T] 对象。

我的自定义对象是这样的

const obj = [{parameter:'firstname', direction: 'ASC'},{parameter:'lastname', direction: 'DESC'}]

如何将obj 转换为[['firstname':'ASC'],'lastname':'DESC'] 之类的数组?

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案1】:

    来自docs

    sortArrayOrObject arrayobject 定义要排序的列、顺序和方向的元组或对象数组,例如[['name', 'ASC'], ['city', 'DESC']]{ name: 'ASC', city: 'DESC' }

    您可以使用Array.prototype.map 将输入数组转换为元组数组。

    const arr = [{ parameter: 'firstname', direction: 'ASC' }, { parameter: 'lastname', direction: 'DESC' }]
    
    const result = arr.map((item) => [item.parameter, item.direction])
    
    console.log(result)

    或者您可以使用Array.prototype.reduce 将输入数组转换为对象。

    const arr = [{ parameter: 'firstname', direction: 'ASC' }, { parameter: 'lastname', direction: 'DESC' }]
    
    const result = arr.reduce((acc, item) => ({
      ...acc,
      [item.parameter]: item.direction,
    }), {})
    
    console.log(result)

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2014-06-11
      • 2021-03-17
      • 2020-12-15
      • 2019-06-08
      • 1970-01-01
      • 2022-08-18
      • 2022-10-13
      相关资源
      最近更新 更多