geekcoder
geekcoder

Reputation: 15

result.data.data.map is not a function

There are similar questions like this , but I didn't find a better solution. I'm calling an API from my Angular JS client side like this

    export default function (
  $http,
  API_URL
) {
  'ngInject'

  const service = {}

  service.searchAddresses = function (searchTerm) {
    return $http.get(`${API_URL}/names/?beginning=${searchTerm || ''}`)
      .then((result) => {

        return result.data.data.map((address) => address.attributes.display) 
      })
  }

  return service
}

In client side, when I console log the result it look like this

{"data":{"data":{"type":"address","attributes":[{"address":"5-7 east street, lidcombe, nsw 2141","display":"5-7 East Street, LIDCOMBE, NSW 2141"},{"address":"5-7 mary street, auburn, nsw 2144","display":"5-7 Mary Street, AUBURN, NSW 2144"},{"address":"5-7 nicholas street, lidcombe, nsw 2141","display":"5-7 Nicholas Street, LIDCOMBE, NSW 2141"}]}}

Then, in API side, network response is like this.

    {
  "data": {
    "type": "address",
    "attributes": [
      {
        "address": "5-7 east street, lidcombe, nsw 2141",
        "display": "5-7 East Street, LIDCOMBE, NSW 2141"
      },
      {
        "address": "5-7 mary street, auburn, nsw 2144",
        "display": "5-7 Mary Street, AUBURN, NSW 2144"
      },
      {
        "address": "5-7 nicholas street, lidcombe, nsw 2141",
        "display": "5-7 Nicholas Street, LIDCOMBE, NSW 2141"
      }
    ]
  }
}

I'm getting an error in client side when I try to retrieve above data. Error is result.data.data.map is not a function

Upvotes: 0

Views: 621

Answers (1)

samanime
samanime

Reputation: 26557

map () is an array function. Your result.data.data is an object. If you want to loop through them, use either Object.keys(), Object.values(), or Object.entries() first:

Object.entries(result.data.data).map(([key, value]) => console.log(key, value))

Upvotes: 3

Related Questions