Underscore.js :迭代 json 对象并使用 _.has() 检查密钥可用性

Underscore.js : iterate json object and check key availability using _.has()

我是 underscore.js 新手,我正在尝试遍历 JSON 对象并检查某些字段是否存在。在这种情况下,我需要找出与输入最匹配的all_rec中的记录。

input = {first_name: "John", surname: "Paul", email: "john.paul@gmail.com"}

all_rec = [
    {"id": 1,"first_name": "John","surname": "Paul","email": "john.paul@gmail.com"},
    {"id": 2,"first_name": "Kerry","surname": "Morrison","phone": "43567823"},
    {"id": 3,"first_name": "John", "phone": "0345433234"}
]

我希望检索到以下记录,

id : 1 ==> Matching all 3 fields ( firstname, surname  & email)
id : 3 ==> Matching only firstname (absence of surname & email)

我尝试了以下代码,

let resultData = _.where(all_rec,  (
    (_.has(all_rec, "first_name") ? {first_name: input.first_name} : true) &&
    (_.has(all_rec, "surname") ? {surname: input.surname} : true) &&
    (_.has(all_rec, "email") ? {email: input.email} : true) &&
    (_.has(all_rec, "mobile") ? {mobile: input.mobile} : true)));

我希望它能带出 ID 为:1 和 3 的记录。但是,它带出了所有记录。不确定我哪里出错了。

此外,我不确定是否可以使用 underscore.js 实现。请指教。

我不确定你是否可以使用 where/findWhere 函数来实现,但你肯定可以使用 filter

来实现

下划线示例:

const input = {
  first_name: "John",
  surname: "Paul",
  email: "john.paul@gmail.com"
};

const all_rec = [
    {"id": 1,"first_name": "John","surname": "Paul","email": "john.paul@gmail.com"},
    {"id": 2,"first_name": "Kerry","surname": "Morrison","phone": "43567823"},
    {"id": 3,"first_name": "John", "phone": "0345433234"}
];

const resultData = _.filter(all_rec, item => 
  _.keys(item).every(key => _.has(input, key) ? input[key] === item[key] : true));

console.log(resultData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

香草 ES6 示例:

const input = {
  first_name: "John",
  surname: "Paul",
  email: "john.paul@gmail.com"
};

const all_rec = [
    {"id": 1,"first_name": "John","surname": "Paul","email": "john.paul@gmail.com"},
    {"id": 2,"first_name": "Kerry","surname": "Morrison","phone": "43567823"},
    {"id": 3,"first_name": "John", "phone": "0345433234"}
];

const resultData = all_rec.filter(item => 
  Object.keys(item).every(key => input.hasOwnProperty(key) ? input[key] === item[key] : true));

console.log(resultData);

下面的函数实现 _.has 并将 return 根据输入的属性和那些可用记录进行匹配。

input = {first_name: "John", surname: "Paul", email: "john.paul@gmail.com"}

all_rec = [
    {"id": 1,"first_name": "John","surname": "Paul","email": "john.paul@gmail.com"},
    {"id": 2,"first_name": "Kerry","surname": "Morrison","phone": "43567823"},
    {"id": 3,"first_name": "Sue", "phone": "0345433234"}
]

const matcher = (input, all_records) => {
    return all_records.filter(record => {
        const keysToUse = Object.keys(record).filter(key => _.has(input, key));
        if (keysToUse.length === 0) return false;
        return keysToUse.every(key => input[key] === record[key]);
    })
}

console.log(matcher(input, all_rec));