gpt4 book ai didi

javascript - 如何在 Javascript 中过滤精确值?

转载 作者:行者123 更新时间:2023-12-05 02:29:50 24 4
gpt4 key购买 nike

我想要红色和大小为 4gb 的地方只输出准确的值,但我得到的地方大小为 4 gb 但颜色为绿色,请在这方面帮助我。我正在制作一个过滤器选项,我的代码是相同的,所以如果可能的话,请把它作为我的代码,否则你也可以建议我如何实现这个?

const x = [
{
color: "green",
name: "123",
size: "4gb"
},
{
color: "red",
name: "555",
size: "4gb"
},
{
color: "green",
name: "123",
size: "2gb"
},
{
color: "blue",
name: "111",
size: "2gb"
},
{
color: "green",
name: "123",
size: "4gb"
},
{
color: "red",
name: "000",
size: "4gb"
}
]

const op = [{
key: "color",
item: "red"
},
{
key: "size",
item: "4gb"
}];

const fil = x.map(l => op.map(o => l[o.key] === o.item && l)).flat().filter(Boolean);

console.log(fil);

输出应该是:

[{
color: "red",
name: "555",
size: "4gb"
},{
color: "red",
name: "000",
size: "4gb"
}];

最佳答案

你应该filter()而不是 map() .

您想要执行的主要操作是 filter(),这意味着结果包含的值少于或等于原始数组中的值,因此原始数组中的每个项目可能会也可能不会出现在结果中,所以如果你想要一个 1:1/0 映射。映射始终返回与描述 1:1 映射的原始数组中相同数量的值,因此得名 map()

另外使用every()遍历过滤器。这将确保满足all/every(同样,名称告诉您是做什么的)过滤条件。

const x = [
{
color: "green",
name: "123",
size: "4gb",
},
{
color: "red",
name: "555",
size: "4gb",
},
{
color: "green",
name: "123",
size: "2gb",
},
{
color: "blue",
name: "111",
size: "2gb",
},
{
color: "green",
name: "123",
size: "4gb",
},
{
color: "red",
name: "000",
size: "4gb",
},
];

const op = [
{
key: "color",
item: "red",
},
{
key: "size",
item: "4gb",
},
];

const fil = x.filter(option => op.every(({key, item}) => option[key] === item));
console.log(fil);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在 Javascript 中过滤精确值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72012455/

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