首页 > 解决方案 > Underscore.js :迭代 json 对象并使用 _.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 来实现。好心提醒。

标签: javascriptnode.jsunderscore.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);


推荐阅读