gpt4 book ai didi

javascript - 如何过滤一组必须满足javascript中所有条件的记录

转载 作者:行者123 更新时间:2023-12-03 01:42:21 28 4
gpt4 key购买 nike

我有一组对象,这些对象具有一些基于所选对象的可过滤信息。

我有以下内容,想迭代 selected 中的键并且仅返回满足所有条件的项目(在本例中用户 AmbertagId 为 12 并且 placementId 为 27)。

需要注意的是,如果 selected filter 等于 null,则应将其排除在过滤之外,因为这意味着用户未按此进行过滤。

这将增长到大约 8 个过滤器,因此不想做一些大的 if 语句。我怎么能这样做呢?

var selected = {};
selected["tagId"] = 12;
selected["placementId"] = 27;
selected["locationId"] = null;

var users = [];
users.push({"name":"Joe", "tagIds":[3,4,12], "placementIds": [2,19]});
users.push({"name":"Suzy", "tagIds":[3,4], "placementIds": [2,19, 27]});
users.push({"name":"Amber", "tagIds":[1,12], "placementIds": [2,19, 27]});

function filterBySelected(items){
var hits = [];
console.log('within filter by Selected');
console.log(items);
for (var key in selected){
if(selected[key]){ //
console.log('you are filtering by: ' + key);
}
}
return hits;
}
var items = filterBySelected(users);
// items should return user object of "Amber"

最佳答案

您可以使用Array#filterObject.entries(或其polyfill),如下所示:

var selected = {tagId: 12,placementId: 27};

var users = [
{"name":"Joe", "tagIds":[3,4,12], "placementIds": [2,19]},
{"name":"Suzy", "tagIds":[3,4], "placementIds": [2,19, 27]},
{"name":"Amber", "tagIds":[1,12], "placementIds": [2,19, 27]}
];

function filterBySelected(items){
return items.filter(item =>
Object.entries(selected).every(([k, v]) =>
v == null || (item[k+"s"] || []).includes(v)
)
);
}

var items = filterBySelected(users);

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何过滤一组必须满足javascript中所有条件的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50778561/

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