gpt4 book ai didi

javascript - Underscore.js : iterate json object and check key availability using _. 有()

转载 作者:搜寻专家 更新时间:2023-10-31 23:49:55 27 4
gpt4 key购买 nike

我是 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>

Vanilla 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);

关于javascript - Underscore.js : iterate json object and check key availability using _. 有(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432288/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com