[英]Display array elements from array of objects using the index obtained from another mapped array
As title suggest, I am trying to get object from an array using the index obtained from another separate array.正如标题所示,我正在尝试使用从另一个单独数组获得的索引从数组中获取 object。 I get error: Uncaught TypeError: venues[index].map is not a function.
我收到错误:未捕获的类型错误:场所 [索引].map 不是 function。
venues = [
{id: 4, title: "bro"}, {id: 5, title: "np bro"}
]
cityArray = [4, 5, 5, 4, 5, 5]
Above is the venues and cityArray.上面是场地和cityArray。
I get the index correctly.我正确地得到了索引。 dispatches works correctly.
调度工作正常。
const Home = () => {
const { city } = useParams();
const featured = useSelector((state) => state.featuredList.featured);
const venues = useSelector((state) => state.venueList.venues);
useEffect(() => {
dispatch(listVenues())
}, [dispatch])
useEffect(() => {
dispatch(listFeatured())
}, [dispatch])
useEffect(() => {
if (city === "perth") {
setCityArray(featured?.featured_perth)
}
}, [featured, city])
return (
<GridWrapper>
{cityArray?.map((i) => {
var index = venues?.findIndex(ar => parseInt(ar.id) === i);
return (
<div>
{venues[0].map(arr =>
(
<div>
<h1>{arr.title}</h1>
</div>
)
)}
</div>
)
}
)}
</GridWrapper>
)
}
export default Home;
Since venues
is an array of objects, you should be able to access the title property with:由于
venues
是一个对象数组,您应该能够通过以下方式访问 title 属性:
return (
<GridWrapper>
{cityArray?.map((i) => {
var index = venues?.findIndex((ar) => parseInt(ar.id) === i);
return (
<div>
<h1>{venues[index].title}</h1>
</div>
);
})}
</GridWrapper>
);
Your error Uncaught TypeError: venues[index].map is not a function
is because venues[index]
refers to an object not an array and objects don't implement a map
method. Your error
Uncaught TypeError: venues[index].map is not a function
is because venues[index]
refers to an object not an array and objects don't implement a map
method.
If you want to continue looking up each object individually, you can simply use find()
instead of findIndex()
to return the object itself.如果您想继续单独查找每个 object,您可以简单地使用
find()
而不是findIndex()
来返回 object 本身。 (You should probably be accounting for elements that aren't found as well). (您可能也应该考虑未找到的元素)。
return (
<GridWrapper>
{cityArray?.map((i) => {
var venue = venues?.find((ar) => parseInt(ar.id) === i);
return (
<div>
<h1>{venue.title}</h1>
</div>
);
})}
</GridWrapper>
);
But if you're going to be doing this repeatedly you should create a Map
or object indexed by id
and access it directly.但是,如果您要重复执行此操作,您应该创建一个由
id
索引的Map
或 object 并直接访问它。
const venues = [
{ id: 4, title: "bro" },
{ id: 5, title: "np bro" }
];
const cityArray = [4, 5, 5, 4, 5, 5];
const venueMap = new Map(venues.map(v => [v.id, v]));
return (
<GridWrapper>
{cityArray?.map((id) => {
const venue = venueMap.get(id);
return (
<div>
<h1>{venue.title}</h1>
</div>
);
})}
</GridWrapper>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.