我想循环遍历对象,检查是否至少有订单颜色或子产品订单颜色是黑色还是红色。
如果至少有一个订单颜色或子产品订单颜色为黑色或红色,则应隐藏"隐藏我"按钮。
下面是的代码
function Parent() {
const product = {
items: [
{
id: '1',
orders: [
{
id: '1',
color: 'red',
},
{
id: '2',
color: 'green',
}
],
subProducts: [
{
id: '1',
orders: [
{
id: '4',
color: 'green',
}
],
}
]
},
{
id: '2',
orders: [
{
id: '3',
color: 'black',
},
{
id: '4',
color: 'blue',
}
],
subProducts: [
{
id: '2',
orders: [
{
id: '5',
color: 'green',
},
{
id: '6',
color: 'black',
}
],
}
]
}
]
}
return (
< Menu > Hide me < / Menu >
);
}
我试过什么
function Parent() {
const checkArray = (array: any[]) => {
for (const item of array) {
if (item.color === 'black' || item.color === 'red') {
return true;
}
}
return false;
};
const output = () => {
let hideBool = false;
if (product.items) {
for (const item of product.items) {
if (hideBool) {
break;
}
if (item.orders) {
hideBool = checkArray(item.orders);
}
if (!hideBool) {
if (item.subProducts) {
for (const subProduct of item.subProducts) {
if (subProduct.orders) {
hideBool = checkArray(subProduct.orders);
}
if (hideBool) {
break;
}
}
}
}
}
}
return hideBool;
};
const isColor = output();
return (
{!isColor &&
<Menu> Hide me </Menu>
}
);
}
上面的片段是有效的。但是,由于有很多if条件,代码看起来很笨拙。如何使用typescript和react来进一步重构这个片段。
有人能帮我做这个吗。谢谢
您可以使用some而不是for循环。它需要更少的代码行,但它是否更可读还有待商榷。
const shouldHide = items.some(item =>
//Check if item.orders have the color
item.orders && item.orders.some(order =>
order.color === "black" || order.color === "red") ||
//Check if item.subProducts.orders have the color
item.subProducts && item.subProducts.some(subProduct =>
subProduct.orders && subProduct.orders.some(order =>
order.color === "black" || order.color === "red"
))
)