【发布时间】:2018-09-25 01:50:04
【问题描述】:
希望找到一种比我目前的解决方案(包括在内)更有效的方法来处理以下问题。
我有以下描述用户的数组:
const userFields = [
{key: "name", value: "tyler"},
{key: "location", value: "boston"},
{key: "phone", value: "555-555-5555"},
{key: "email", value: "tyler@test.com"}
]
和一个列出允许的主要字段的数组(一些是必需的,一些是可选的):
const primaryFields = [
{ key: "name", alias: ["nickname"], required: true },
{ key: "address", alias: ["location", "homebase"], required: true },
{ key: "age", alias: [], required: true },
{ key: "phone", alias: [], required: false },
{ key: "gender", alias: [], required: false }
]
希望使用 primaryFields 数组中提供的信息验证 userFields 数组,并生成三种可能的输出:主要字段(对象)、次要字段(数组)、缺失字段(数组)。此外,还有一些注意事项,1. userFields 应该由键或别名识别,2. 主字段的键应该是 primaryFields 数组中使用的键的键(如果在 userFields 中使用别名)。
所以上面应该输出:
{
primary:{
name: "tyler",
address: "boston",
phone: "555-555-5555"
},
secondary: [
{key: "email", value: "tyler@test.com"}
],
missing: ["age"]
}
这是一个包含我的解决方案的要点: https://gist.github.com/tilersmyth/26984866d7428c9b502ec8971d961997
基本流程是:
- 遍历 userFields 以根据 PrimaryField 键(如果使用别名)更新键并记录这些键(以检查是否需要)
- 检查缺少的必填字段
- 确定将作为辅助项推送的剩余用户字段
对一种更有效的方法有何见解?
【问题讨论】:
标签: javascript arrays sorting filter ecmascript-6