javascript – 使用模糊匹配查找集合中的对象

我有一个看起来像这样的集合:

const collection = [
    {
        name: 'THIS_ITEM',
        conditions: {
            oneCondition: false,
            anotherCondition: false,
            yourCondition: false,
            myCondition: false
        }
    }, {
        name: 'THAT_ITEM',
        conditions: {
            oneCondition: false,
            anotherCondition: false,
            yourCondition: true,
            myCondition: false
        }
    }, {
        name: 'THOSE_ITEMS',
        conditions: {
            oneCondition: true,
            anotherCondition: false,
            yourCondition: null,
            myCondition: false
        }
    }
];

……以及后来看起来像这样的对象:

const condition = {
    oneCondition: true,
    anotherCondition: false,
    yourCondition: true,
    myCondition: false
};

我正在尝试将条件对象与集合中的嵌套条件对象进行匹配,以找到匹配的对象,这样我就可以从匹配的条目中检索name属性.

抛弃循环的事情是条件属性可以具有“模糊”值.我的意思是,如果源集合中的任何属性设置为true或false,它们必须完全匹配条件中的值.但是,如果源集合中的属性值为null,则它可以匹配true或false.

例:

这些将匹配:

const condition = {
    oneCondition: true,
    anotherCondition: false,
    yourCondition: true,
    myCondition: false
};

const collection = [
    …
    }, {
        name: 'THOSE_ITEMS',
        conditions: {
            oneCondition: true,
            anotherCondition: false,
            yourCondition: null,
            myCondition: false
        }
    }
];

这些不会:

const condition = {
    oneCondition: true,
    anotherCondition: false,
    yourCondition: true,
    myCondition: false
};

const collection = [
    …
    }, {
        name: 'THAT_ITEM',
        conditions: {
            oneCondition: false,
            anotherCondition: false,
            yourCondition: true,
            myCondition: false
        }
    }, {
    …
];

有什么建议?我正在使用Lodash,但似乎无法想象没有过于冗长和嵌套的混合物的任何解决方案.

解决方法:

您可以将Array#filterArray#every一起用于条件,并将空值作为通配符进行测试.

var collection = [{ name: 'THIS_ITEM', conditions: { oneCondition: false, anotherCondition: false, yourCondition: false, myCondition: false } }, { name: 'THAT_ITEM', conditions: { oneCondition: false, anotherCondition: false, yourCondition: true, myCondition: false } }, { name: 'THOSE_ITEMS', conditions: { oneCondition: true, anotherCondition: false, yourCondition: null, myCondition: false } }],
    condition = { oneCondition: true, anotherCondition: false, yourCondition: true, myCondition: false },
    result = collection.filter(o =>
        Object.keys(condition).every(k =>
            o.conditions[k] === null || o.conditions[k] === condition[k]
        )
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
上一篇:通过zabbix自带模板监控windowsPC机器


下一篇:基于序列javascript拆分数组