使用可选值过滤集合

时间:2018-07-24 11:53:10

标签: javascript

我有一个问题:我知道如何使用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}

我如何实现这样的目标?

2 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:0)

您可以获取键和值并针对该对象进行补偿以进行过滤。

var 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 } }], 
    filter = { category: "country", access: 2 },
    result = data.filter(({ paths }) =>
        Object.entries(filter).every(([k, v]) => paths[k] === v));

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