Thoughts:
- use
.filter
to filter the array based on a function, docs
- use
.find
to check whether each item has your desired property, in this case, a tag with the name sales
, docs
const array = [
{
tags: [
{
name: "Hit",
slug: "hit"
},
{
name: "Sale",
slug: "sale"
}
],
price: 6000,
stock: 10,
name: "Name Product",
description: "Test",
slug: "name-product"
},
{
tags: [
{
name: "Sale",
slug: "sale"
}
],
price: 6000,
stock: 10,
name: "Name Product 2",
description: "Test 2",
slug: "name-product-2"
},
{
tags: [
{
name: "NotSale",
slug: "notsale"
}
],
price: 6000,
stock: 10,
name: "Name Product 2",
description: "Test 2",
slug: "name-product-2"
}
];
const filteredArray = array.filter((t) => {
return t.tags && t.tags.find((tag) => tag.name.toLowerCase() === "sale");
});
console.log(filteredArray);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…