我有这个来自 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" }
}
您需要在某处包含有关哪些类型是数字的附加信息。该解决方案将这些存储在一个数组中,将该数组传递给一个函数,并取回一个函数,该函数接受一个列数组并返回一个字段定义对象。
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
}, {})
}
}
您在运行此代码时遇到问题。我猜你提供的参数不正确。请注意,此版本要求您传递数值列表以返回一个函数,然后您将使用列列表调用以返回类型的对象。也就是说,你必须这样称呼它:
// 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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句