React 数组遍历判断属性值是否相同,返回对应元素
你可以使用Array.prototype.filter()方法来遍历数组并根据指定属性值进行过滤。然后根据过滤结果返回相应的React元素。
以下是一个示例代码:
import React from 'react';
const data = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'John' },
{ id: 4, name: 'Mike' },
];
const MyComponent = () => {
const filteredItems = data.filter(item => item.name === 'John');
if (filteredItems.length === 1) {
return <div>Found 1 item with name John</div>;
} else if (filteredItems.length > 1) {
return (
<div>
Found {filteredItems.length} items with name John:
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
} else {
return <div>No items found with name John</div>;
}
};
export default MyComponent;
上述代码中,我们先使用filter()方法过滤出name属性值为'John'的项,然后根据filteredItems数组的长度返回相应的React元素。如果长度为1,则返回一个表示找到1个项的React元素;如果长度大于1,则返回一个表示找到多个项的React元素,并使用map()方法生成相应的列表;如果长度为0,则返回一个表示未找到任何项的React元素。
原文地址: https://www.cveoy.top/t/topic/dyit 著作权归作者所有。请勿转载和采集!