JSON嵌套结构属性访问返回undefined的问题分析
data.pre Returns Undefined & How to Fix It Let’s break down exactly what’s happening here, and how to resolve the issue.
The Root Cause
Your original myData structure has a nested hierarchy you’re not accounting for:
myData = {"data":[{"pre":1,"post":2}]}
Let’s unpack this step by step:
myDatais a top-level object with one property:data.- The
dataproperty’s value is an array (marked by square brackets[]) containing a single inner object. - That inner object holds the
preandpostproperties you want to access.
When you try to call data.pre (or myData.pre), you’re asking for a pre property directly on the top-level object—but that property doesn’t exist! The top-level object only has a data property, hence the undefined result.
When you simplified the structure to {"pre":1,"post":2}, you moved those properties directly onto the top-level object, so data.pre works because the property now exists at that level.
Fixes to Access the pre Value
Depending on your needs, here are the correct ways to get the pre value from the original structure:
1. Access the Nested Property Correctly
If you need to keep the original array structure, traverse down to the inner object properly:
// Assuming your variable is named myData console.log("data.pre: " + myData.data[0].pre); // Output: 1
Let’s break this down:
myData.data: Retrieves the array from the top-level object.[0]: Accesses the first (and only) element in the array..pre: Gets thepreproperty from that inner object.
2. Simplify the Structure (If Possible)
If you don’t need the array wrapper around the object (since it only contains one element), you can adjust myData to remove the array, just like you did:
myData = {"pre":1,"post":2} console.log("data.pre: " + myData.pre); // Output: 1
This works because pre is now a direct property of the top-level object.
3. Check for Variable Name Typos
In your console log, you used data.pre but your variable is named myData. If that’s not a typo in your question, make sure you’re using the correct variable name! For example:
// If you assigned data = myData earlier: const data = myData; console.log("data.pre: " + data.data[0].pre); // Still need the nested access
Quick Recap
undefinedoccurs when you try to access a property that doesn’t exist on the object you’re querying.- Always match your property access to the actual structure of your data.
- Arrays require index access (
[0]) to retrieve their elements before you can access properties on those elements.
内容的提问来源于stack exchange,提问作者Kiwi

