数组对象转对象

开发中会遇到,从前端拿到数据类型如下:

const options = [
  { label: 'name', value: 'xxx' },
  { label: 'age', value: 23 },
]

但是后端需要的数据如下:

const options = {
  name: 'xxx',
  age: 23,
}

解决方案:

interface Option {
  label: string
  value: any
}

const options: Option[] = [
  { label: 'name', value: 'xxx' },
  { label: 'age', value: 23 },
]

const result = options.reduce<Record<string, any>>((prev, curr) => {
  prev[curr.label] = curr.value
  return prev
}, {})

DreamFightter
5 声望0 粉丝