如何在JavaScript中生成多层嵌套对象?实现太阳系层级访问结构
Got it, let's fix that nested object structure so you can access properties like universe.system1.planet4.x easily. The issue with your current code is that you're directly adding planet properties to the top-level universe object, skipping the system layer entirely. We need to build each level step by step: first create the system objects, then populate each system with planets, each of which holds your target properties.
Here's a working implementation that builds the full universe > system > planet > [properties] hierarchy:
setInterval(onTimerTick, 1000); function onTimerTick() { const systemCount = 2; // Adjust number of systems as needed const planetsPerSystem = 4; // Number of planets per system // Reset universe each tick (remove this line if you want to persist data across ticks) universe = {}; // First loop: create each system in the universe for (let sysNum = 1; sysNum <= systemCount; sysNum++) { const systemKey = `system${sysNum}`; // Initialize the system as an empty object (critical for nesting!) universe[systemKey] = {}; // Second loop: populate the current system with planets for (let planetNum = 1; planetNum <= planetsPerSystem; planetNum++) { const planetKey = `planet${planetNum}`; // Add a planet object with your desired properties universe[systemKey][planetKey] = { x: Math.floor(Math.random() * 100), // Example dynamic value y: Math.floor(Math.random() * 100), z: Math.floor(Math.random() * 100), placeholderData: [systemCount, planetsPerSystem, sysNum, planetNum] }; } console.log(`Created ${systemKey} with ${planetsPerSystem} planets`); } // Test the multi-level access you wanted console.log("Direct property access example:", universe.system1.planet4.x); console.log("Full universe structure:", universe); } // Initialize the top-level universe object let universe = {};
Key Fixes & Explanations:
- Layered Construction: We first create each
systemas an empty object insideuniversebefore adding planets to it. This is essential—you can't add properties to a non-existent object! - Nested Loops: The outer loop handles systems, the inner loop handles planets within each system. This builds the exact hierarchy you need.
- Accessible Properties: Each planet is an object with explicit properties (like
x,y,z) so you can access them directly with dot notation (universe.system1.planet4.x). - Optional Persistence: If you don't want to reset the universe every tick, remove the
universe = {};line—just make sure to use unique keys if you're adding new systems/planets over time (e.g., append a timestamp to avoid overwriting).
Your original code only added planets directly to universe, which is why you couldn't get the multi-level nesting. By explicitly creating each intermediate layer as an object, you unlock the nested access pattern you're aiming for.
内容的提问来源于stack exchange,提问作者Joshua Rosser

