如何从Pannellum插件返回的JSON数组中提取指定值
Hey there! I see you're trying to pull the sid and sceneId fields from the hotSpots array in your Pannellum plugin data, and hitting a wall with console.log(hotSpots.sid)—let's fix that!
The Issue
The hotSpots property in your hs2 object is an array of objects, not a single object. When you try to access hotSpots.sid directly, you're asking the array itself for a sid property (which it doesn't have) instead of looking at each individual item inside the array.
The Solution
You need to iterate over each element in the hotSpots array to access the sid and sceneId fields for every hotspot. Here are a couple of straightforward ways to do this:
1. Using forEach to log or process each entry
If you just want to view or handle each hotspot's data one by one:
// First, get the hotSpots array from your hs2 object const hotSpots = hs2.hotSpots; // Loop through each hotspot in the array hotSpots.forEach(hotSpot => { // Extract the fields from the current hotspot object const { sid, sceneId } = hotSpot; // Do whatever you need with these values—log them, store them, etc. console.log(`Hotspot sid: ${sid}, sceneId: ${sceneId}`); });
2. Using map to create a new array of extracted data
If you want to collect all the sid and sceneId pairs into a new array for later use:
// Create a new array containing only the fields we need const extractedHotspotData = hs2.hotSpots.map(hotSpot => ({ sid: hotSpot.sid, sceneId: hotSpot.sceneId })); // Now you have a clean array of objects with just sid and sceneId console.log(extractedHotspotData);
Quick Check
Before diving in, you can confirm the structure by logging the hotSpots array first:
console.log(hs2.hotSpots);
This will show you that it's an array, where each index holds an object with your target fields.
内容的提问来源于stack exchange,提问作者Wilf

