首页 > 解决方案 > 如何根据客户的输入动态查找用户?[解决了]

问题描述

我正在尝试提供一种更动态的方式来根据用户的输入查找 Person 是否存在。我真的只是在寻找基于这个愚蠢例子的动态方式:

输入字段示例

let inputField = [
{
  name: 'John Smith',
  age: 25,
  married: true
  best_contact: 'email'
},
{
  name: 'John Smith',
  age: 24,
  married: false,
  best_contact: 'email'
},
{
  name: 'John Smith',
  age: 39,
  married: false,
  best_contact: 'phone'
}
]

用户输入示例

let user = {
  name: 'John Smith',
  age: 39,
  married: false,
  best_contact: 'email'
}

我的档案...

// this is what i have so far

inputField.map(input => {
  return input.find(person => {
    let userKeys = Object.keys(user);
    let result = userKeys.reduce((a, v)) => {
      if(v && person.hasOwnProperty(v)) {
        if(v && input[v] === person[v]) a++;

        else if(['phone', 'email', 'in-person'].includes(v) && person[v]) a++;

        // age condition here i will leave out
      }
     return a;
    }
    return result === userKeys.length; // returns the inputField obj regardless matches users input value
  }
}
// this should return false or nothing

在这种情况下,它应该不返回任何内容,因为结婚后的值不匹配。无论如何,我都会得到一场比赛,我相信我们这里的社区对此有一个更清洁、更动态的解决方案。我可以指定姓名、年龄、已婚、最好的联系方式,但我想要一个更简单的方法来做到这一点。

标签: javascriptalgorithmecmascript-6ecmascript-2016

解决方案


推荐阅读