2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
const filteredProducts = products.filter(p => p.type.includes(type));
.filter
您可以在外部數(shù)組和.includes
內(nèi)部數(shù)組上使用來(lái)執(zhí)行您要查找的操作。
根據(jù)記錄,“berry”從未出現(xiàn)在任何“type”數(shù)組中,但“berry”卻出現(xiàn)在

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用Array.prototype.filter()withArray.prototype.some()來(lái)獲取過(guò)濾結(jié)果。如果數(shù)組中至少有一個(gè)元素通過(guò)給定回調(diào)函數(shù)的測(cè)試,則 some() 方法返回 true。
const filterValue = 'berry';
const products = [
{
id: 1,
productName: 'Strawberry Basil',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Cherry_Pop_Still_4K_Front-CherryPop.png?v=1588713373',
type: ['berry', 'citrusy', 'fancy'],
price: 5.5,
},
{
id: 2,
productName: 'Sour Blueberry',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/SourBlueBerry_Still_4K_Front-SourBlueberry.png?v=1588713584',
type: ['all', 'sour', 'berry'],
price: 4,
},
{
id: 3,
productName: 'Blackberry Jam',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/BlackBerry_Jam_Still_4K_Front-BlackberryJam.png?v=1595035965',
type: ['all', 'berry'],
price: 10,
},
{
id: 4,
productName: 'Orange Nectarine',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Orange_Nectarine_Still_4K_Front-OrangeNectarine.png?v=1588713522',
type: ['all', 'Citrus', 'fancy', 'juicy'],
price: 6,
},
{
id: 5,
productName: 'Lemon Verbena',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/Lemon_Verbena_Still_4K_Front-LemonVerbena.png?v=1588713474',
type: ['all', 'Citrus', 'classic', 'floral'],
price: 4.5,
},
{
id: 6,
productName: 'Extra Peach',
productImgURL:
'https://cdn.shopify.com/s/files/1/0274/3641/7123/products/ExtraPeach_Still_4K_Front-ExtraPeach.png?v=1588713411',
type: ['Juicy'],
price: 8.5,
},
];
const ret = products.filter(({ type }) =>
type.some((x) => x.toLowerCase() === filterValue.toLowerCase())
);
console.log(ret);
添加回答
舉報(bào)