1

I am using vuejs and axios, I am trying to get blog posts from wordpress, everything working fine except one thing, I am trying to extract the thumbnail from the response, but the response data contains hyphen so I am not able to access the object, showing error. Here is what I am trying to access

family._embedded['wp:featuredmedia']['0'].media_details.sizes.family-profile-thumb.source_url

here family is a prop, and family-profile-thumb is the specific size, I could not change that, this part creating problem, if i replace this with default sizes like thumb it will work, eg:

family._embedded['wp:featuredmedia']['0'].media_details.sizes.thumbnail.source_url

Is there a way to get this work?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Salih K
  • 701
  • 2
  • 12
  • 31
  • `.["family-profile-thumb"].` – Keith Mar 17 '19 at 08:05
  • As I said I am using Vuejs, so in template I am using like this If I replace thumbnail and add as you provided wont work,even if I change double quote to single quote, right? – Salih K Mar 17 '19 at 08:11
  • 1
    You can check this gist https://gist.github.com/hygull/df535d30cdd20afc2a6e17aaa292494b too. – hygull Mar 17 '19 at 08:26

2 Answers2

1

Access it using square bracket notation:

family._embedded["wp:featuredmedia"]["0"].media_details.sizes["family-profile-thumb"].source_url
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Whenever property name is not a valid JS identifier you need to use [] bracket notation to access the property.

What are valid JS identifier ?

  • property name should not start with digit e.g -> 1d
  • Anything other other than alphanumeric, underscore and $ is not valid e.g -> 'hello-world'

let a = {
  "hello-world" : 'some value'
}

console.log(a['hello-world'])
console.log(a.hello-world)

You can read here for further information MDN reference

Code Maniac
  • 37,143
  • 5
  • 39
  • 60