首页 > 解决方案 > 将响应从 api 转换为具有特定格式的对象

问题描述

我有这个来自 api 的回复

columns: Array(4)
0: "Id"
1: "Title"
2: "Description"
3: "IsActive"

我需要将它转换为这种格式,所以会有“字段”,在字段下它列出了来自 api 响应的值,并且在每个值上都会有一个类型,我还需要确定它是 Id 还是 IsActive 然后它将是数字。我只允许遵循这种特定的对象格式,而且我需要支持 IE 浏览器

fields: {
Id: { type: "number" },
Title: { type: "string" },
Description: { type: "string" },
IsActive: { type: "number" }
}

标签: javascript

解决方案


您需要在某处包含有关哪些类型是数字的附加信息。该解决方案将它们存储在一个数组中,将该数组传递给一个函数,然后返回一个函数,该函数接受一个列数组并返回一个字段定义对象。

const makeFields = (numericTypes) => (columns) => columns.reduce(
  (a, s) => ({...a, [s]: {type: numericTypes.includes(s) ? 'numeric' : 'string'}}),
  {}
)

const numericTypes = ['Id', "IsActive"]
const columns = ["Id", "Title", "Description", "IsActive"]

console.log(makeFields(numericTypes)(columns))

您可以使用类似的东西保存该中间函数,const makeMyFields = makeFields(numericTypes)然后将其用作makeMyFields(columns)

更新

这是另一个应该在 IE 中工作的版本(未经测试):

const makeFields = function(numericTypes) {
  return function(columns) {
    return columns.reduce(function(a, s) {
      a[s] = {type: numericTypes.includes(s) ? 'numeric' : 'string'}
      return a
    }, {})
  }
}

更新 2

您在运行此代码时遇到问题。我猜你提供的参数不正确。请注意,此版本要求您传递数值列表以取回一个函数,然后您将使用列列表调用该函数以取回该类型的对象。也就是说,你必须这样称呼它:

// makeFields (numericTypes) (columns)
//    ^            ^             ^------ call that new function with column names
//    |             `---- call with list of numeric types, returns a new function
//     `-- function name

更改功能很容易,因此您可以一次性提供所有参数。但这种表述有一个优势。您可以使用数字类型调用外部函数并取回可重用函数。然后可以将该内部函数应用于您选择的任何列集。例如,它可以传递给map,因此如果您有多组列,您可以简单地编写multipleColumns.map(makeFields(numericTypes)).

但是如果你想改变它,新版本可能是这样的:

const makeFields = function(numericTypes, columns) {
  return columns.reduce(function(a, s) {
    a[s] = {type: numericTypes.includes(s) ? 'numeric' : 'string'}
    return a
  }, {})
}

const numericTypes = ['Id', "IsActive"]
const columns = ["Id", "Title", "Description", "IsActive"]

console.log(makeFields(numericTypes, columns))


推荐阅读