gpt4 book ai didi

javascript - 使用可选值过滤集合

转载 作者:行者123 更新时间:2023-11-30 20:20:32 26 4
gpt4 key购买 nike

我有一个问题:我知道如何使用 Array.prototype.filter,但我无法想象如何使用可选键过滤掉项目。例如:

[
{item: 1, paths: {category: "country", name: "England", access: 2},
{item: 3, paths: {category: "country", name: "Russia", access: 2},
{item: 2, paths: {category: "country", name: "Portugal", access: 0}
]

我想通过路径选择性地过滤掉它们,比方说通过对象的形状:

{category: "country", access: 2}

我怎样才能实现这样的目标?

最佳答案

您可以在过滤器中编写一个自定义比较器,将比较器对象的所有值与类似的项目进行比较

const data = [
{item: 1, paths: {category: "country", name: "England", access: 2}},
{item: 3, paths: {category: "country", name: "Russia", access: 2}},
{item: 2, paths: {category: "country", name: "Portugal", access: 0}}
]

const comparator = {category: "country", access: 2};

const compareObjectKeys = (comparator, item) => {
return Object.keys(comparator).every(key => {
return item.paths[key] === comparator[key];
})
}
const res = data.filter(item => {
return compareObjectKeys(comparator, item);
})

console.log(res)

关于javascript - 使用可选值过滤集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51497918/

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