gpt4 book ai didi

javascript - 使用模糊匹配在集合中查找对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:47 24 4
gpt4 key购买 nike

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

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
};

我正在尝试将 condition 对象与 collection 中嵌套的 conditions 对象进行匹配,以找到匹配的对象,以便我可以检索匹配条目中的 name 属性。

让我陷入循环的是 conditions 属性可以有“模糊”值的事实。我的意思是,如果源 collection 中的任何属性设置为 truefalse,它们必须与 condition< 中的值匹配 正是。但是,如果源 collection 中的属性的值为 null,则它可以匹配 either true假的

示例:

这些将匹配:

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对于条件并针对 null 值作为通配符进行测试。

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; }

关于javascript - 使用模糊匹配在集合中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886915/

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