根据另一个数组(JavaScript)验证并格式化数组输出

时间:2018-09-25 01:50:04

标签: javascript arrays sorting filter ecmascript-6

希望找到一种比我当前的解决方案(已包含在内)更有效的方法来解决以下问题。

我有以下描述用户的数组:

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

基本过程是:

  1. 遍历userFields以基于PrimaryField键(如果使用别名)更新键并记录这些键(以检查是否需要)
  2. 检查缺少的必填字段
  3. 标识将作为次要项目推送的其余userFields

是否有任何更有效的方法见解?

1 个答案:

答案 0 :(得分:0)

您可以使用reduce将数组缩小为对象或数组

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 }
 ];
 
const validate = (user, primary) => ({
  primary: user.reduce(
    (p, field) =>
      primary.find(f => field.key === f.key || f.alias.includes(field.key))
        ? { ...p, [field.key]: field.value }
        : p,
    {}
  ),
  secondary: user.reduce(
    (results, field) =>
      !primary.find(f => field.key === f.key || f.alias.includes(field.key))
        ? [ ...results, field ]
        : results,
    []
  ),
  missing: primary.reduce(
    (results, field) =>
      field.required && !user.find(f => f.key === field.key || field.alias.includes(f.key))
        ? [...results, field.key]
        : results,
    []
  )
});
 
 console.log(validate(userFields, primaryFields));