将基于值和数组的对象过滤为值js



我试图创建一个过滤器,当对象是单个值时,该过滤器可以工作,但当引入一组关键字时,我遇到了问题。

我的代码如下所示:

const filter = {
colors: ["white"],
sizes: [9, 12],
brands: ["adidas"],
keywords: ["running", "weights"]
};
const shoes = [{
brand: "adidas",
size: 9,
color: "white",
keywords: ["running"]
},
{
brand: "adidas",
size: 12,
color: "white",
keywords: ["weigths"]
},
{
brand: "nike",
size: 7,
color: "red",
keywords: ["running", "tennis"]
}
];

const properties = {
colors: 'color',
sizes: 'size',
brands: 'brand',
keywords: 'keywords',
}
const filters = Object
.entries(filter)
.filter(([, {
length
}]) => length)
.map(([k, v]) => [properties[k], v]);
const result = shoes.filter(shoe => filters.every(([k, v]) => v.includes(shoe[k])));
console.log('result', result)

我正在寻找的结果是

const results = {
brand: "nike",
size: 9,
color: "white",
keywords: ["running"]
},
{
brand: "adidas",
size: 12,
color: "white",
keywords: ["swimming"]
}]

通过使匹配的单词具有拼写差异,您可以创建每个值的数组,并对照所需的值进行检查。

const
filter = { colors: ["white"], sizes: [9, 12], brands: ["adidas"], keywords: ["running", "weights"] },
shoes = [{ brand: "nike", size: 9, color: "white", keywords: ["running"] }, { brand: "adidas", size: 12, color: "white", keywords: ["weights"] }, { brand: "nike", size: 7, color: "red", keywords: ["running", "tennis"] }],
properties = { colors: 'color', sizes: 'size', brands: 'brand', keywords: 'keywords' },
filters = Object
.entries(filter)
.filter(([, { length }]) => length)
.map(([k, v]) => [properties[k], v]),
result = shoes.filter(
shoe => filters.every(
([k, v]) => [].concat(shoe[k]).some(value => v.includes(value))
)
);
console.log('result', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

我的假设是,你是按sizecolorkeywords过滤,而不是按brand过滤,基于此,我生成了下面的代码,但如果假设无效,请提供更多详细信息

您可以使用array.filter通过传递条件来过滤数组

let result = shoes.filter(f => filter.sizes.includes(f.size) 
&& filter.colors.includes(f.color) 
&& filter.keywords.some(k => f.keywords.includes(k))
)
console.log(result);

以下内容应该过滤掉任何值与过滤器不一致的对象:

const filterObjectArray = (filters, array) => {
return array.filter(obj => {

// iterate through each key in filters
for (let i in filters) {

const objVal = obj[properties[i]]

// here, we can use flatMap to "spread" objVal and filters[i] into
// an array, whether or not objVal is an array
const combinedValues = [objVal, filters[i]].flatMap(x => x)

// convert the combinedValues into a Set to remove duplicates
const set = new Set(combinedValues)

// If the size of the set matches the length of combinedValues
// it means that objVal and filters[i] have no values in common, so we
// can just return false.
if (set.size === combinedValues.length) return false
}

// If we reach here, it means every value in object has been validated by every key/value in filters.
return true
})
}

下面是一个repl,您可以在其中看到这些代码的作用:https://replit.com/@isaacsan123/过滤对象

相关内容

  • 没有找到相关文章

最新更新