AngularJS客户端调用API遇result.data.data.map is not a function错误求助
Hey there, let's break down why you're seeing this error and how to fix it!
What's the root cause?
The map() method only works on arrays. When you get the error map is not a function, it means the value you're calling it on (result.data.data) is NOT an array—it could be a plain object, a string, null, undefined, or something else entirely.
Step-by-step fixes & checks
Let's walk through the most common scenarios and solutions:
First, verify what
result.data.dataactually is
Pop these two lines in your code right before themapcall to debug:console.log("Type of data:", typeof result.data.data); console.log("Actual data:", result.data.data);This will tell you exactly what you're working with.
Scenario 1: API returns a single object instead of an array
If your console showsresult.data.datais an object (like{ id: 1, name: "example" }) instead of an array ([{...}, {...}]), you can wrap it in an array to usemap:// Wrap the object in an array first [result.data.data].map(item => { // Your mapping logic here });Or, if you control the API, adjust it to return an array even for single items (this is more consistent long-term).
Scenario 2: The data is an unparsed JSON string
Sometimes AngularJS's$httpmight not auto-parse the response if the API returns an incorrectContent-Typeheader. If your console shows a string like"{"name":"test"}", parse it first:const parsedData = JSON.parse(result.data.data); // Now use map if parsedData is an array parsedData.map(item => { // Your logic here });Scenario 3:
result.data.datais null/undefined
Add a fallback to an empty array to avoid the error entirely:(result.data.data || []).map(item => { // Your mapping logic here });This way, if the data is missing, it'll just map over an empty array instead of throwing an error.
Example to make it concrete
Suppose your API response looks like this:
{
"data": {
"username": "geekcoder",
"email": "geek@example.com"
}
}
Callingresult.data.data.map(...)will fail because it's an object. Instead, you'd do:
[result.data.data].map(user => { return { displayName: user.username, contact: user.email }; });
内容的提问来源于stack exchange,提问作者geekcoder

