javascript - 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 来实现。好心提醒。
解决方案
我不确定您是否可以使用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);
推荐阅读
- bash - sed 匹配包含特殊字符的多行并替换匹配模式的一部分
- math - 为什么 BigInteger 实现使用符号幅度而不是二进制补码?
- scala - 使用 Window 时的性能问题
- java - 如何使用 SearchCriteria 类在 Spring Data jpa 中用户给出的许多术语上搜索用户
- python - 通过保留最小线宽替换多行字符串中的字符
- java - Java分治算法堆栈溢出错误
- python - 语法错误:解析 _ input.split 时出现意外 EOF
- sql - 如何使用 sql 查询从表中检索图像并将其保存到不同服务器的文件夹中
- .htaccess - 仅将多个域重定向到 https
- microsoft-edge - 呈现超过 50,000 行的表格时的边缘限制